Socket 是任何一种计算机网络通讯中最基础的内容。当你在浏览器地址栏中输入一个地址时,你会打开一个套接字,可以说任何网络通讯都是通过 Socket 来完成的。

Socket 的 python 官方函数 http://docs.python.org/library/socket.html

socket和file的区别:

  1、file模块是针对某个指定文件进行【打开】【读写】【关闭】

  2、socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】

基本流程:

简单的一个端对端单线通信代码如下:

Server:

 # -*- coding:utf-8
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(("0.0.0.0",12800))
sock.listen(2)
while True:
conn,sockname = sock.accept()
print("Now,We have accepted a connection from:",sockname)
print("Socket Name is:",conn.getsockname())
print("Socket Peer is:",conn.getpeername())
message = conn.recv(1024)
print("The message we have received is:\n%s"%message)

Client:


# -*- coding:utf-8
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(("127.0.0.1",12800))
sock.send(b"Hello World!")

参数解释:

 socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): 创建一个套接字对象,所有套接字操作基于此对象进行
  family:套接字协议族,包括:有两种类型的套接字:基于文件的和面向网络的。AF表示地址家族(address family)
    AF_UNIX:该套接字是基于文件的,一般用于本机通信
    
AF_INET:该套接字是基于网络的,这也是最常用的(默认)   
    AF_INET6 用于第6 版因特网协议(IPv6)寻址
  type:套接字类型,常用的有两种:
    SOCK_STREAM:流式socket ,
for TCP (默认)   
    SOCK_DGRAM:数据报式socket , for UDP
    SOCK_RAW 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
    SOCK_RDM 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
    SOCK_SEQPACKET 可靠的连续数据包服务
  proto:协议,与特定的地址家族相关的协议,如果是 0 ,则系统就会根据地址格式和套接类别,自动选择一个合适的协议

sock.bind(address)

  sock.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。

 

sock.listen(backlog)-- 服务端

  开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。

    backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
    这个值不能无限大,因为要在内核中维护连接队列,一般默认值为5

 

 

sock.settimeout(timeout)

 

  设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )

 

sock.getpeername()

 

  返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。

 

sock.getsockname()

 

  返回套接字自己的地址。通常是一个元组(ipaddr,port)

 

sock.fileno()

 

  套接字的文件描述符

 

 

sock.setblocking(bool)

  是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。

sock.accept()-- 服务端

  接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。

  接收TCP 客户的连接(阻塞式)等待连接的到来

sock.connect(address)-- 客户端

  连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。

sock.connect_ex(address)

  同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061

sock.close()

  关闭套接字

 

 

sock.recv(bufsize[,flag])

  接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。

sock.recvfrom(bufsize[.flag])

  与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。

sock.send(string[,flag])

  将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。

sock.sendall(string[,flag])

  将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。

      内部通过递归调用send,将所有内容发送出去。

sock.sendto(string[,flag],address)

  将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。

SocketType.__doc__

 class SocketType(__builtin__.object)
| socket([family[, type[, proto]]]) -> socket object
|
| Open a socket of the given type. The family argument specifies the
| address family; it defaults to AF_INET. The type argument specifies
| whether this is a stream (SOCK_STREAM, this is the default)
| or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
| specifying the default protocol. Keyword arguments are accepted.
|
| A socket object represents one endpoint of a network connection.
|
| Methods of socket objects (keyword arguments not allowed):
|
| accept() -- accept a connection, returning new socket and client address
| bind(addr) -- bind the socket to a local address
| close() -- close the socket
| connect(addr) -- connect the socket to a remote address
| connect_ex(addr) -- connect, return an error code instead of an exception
| dup() -- return a new socket object identical to the current one [*]
| fileno() -- return underlying file descriptor
| getpeername() -- return remote address [*]
| getsockname() -- return local address
| getsockopt(level, optname[, buflen]) -- get socket options
| gettimeout() -- return timeout or None
| listen(n) -- start listening for incoming connections
| makefile([mode, [bufsize]]) -- return a file object for the socket [*]
| recv(buflen[, flags]) -- receive data
| recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
| recvfrom(buflen[, flags]) -- receive data and sender's address
| recvfrom_into(buffer[, nbytes, [, flags])
| -- receive data and sender's address (into a buffer)
| sendall(data[, flags]) -- send all data
| send(data[, flags]) -- send data, may not send all of it
| sendto(data[, flags], addr) -- send data to a given address
| setblocking(0 | 1) -- set or clear the blocking I/O flag
| setsockopt(level, optname, value) -- set socket options
| settimeout(None | float) -- set or clear the timeout
| shutdown(how) -- shut down traffic in one or both directions
|
| [*] not available on all platforms!
|
| Methods defined here: |
| accept(self)
| accept() -> (socket object, address info)
|
| Wait for an incoming connection. Return a new socket representing the
| connection, and the address of the client. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| bind(self, address) | bind(address)
|
| Bind the socket to a local address. For IP sockets, the address is a
| pair (host, port); the host must refer to the local host. For raw packet
| sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
|
| close(self)
| close()
|
| Close the socket. It cannot be used after this call.
|
| connect(self, address)
| connect(address)
|
| Connect the socket to a remote address. For IP sockets, the address
| is a pair (host, port).
|
| connect_ex(self, address)
| connect_ex(address) -> errno
|
| This is like connect(address), but returns an error code (the errno value)
| instead of raising an exception when an error occurs.
|
| fileno(self)
| fileno() -> integer
|
| Return the integer file descriptor of the socket.
|
| getpeername(self)
| getpeername() -> address info
|
| Return the address of the remote endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockname(self)
| getsockname() -> address info
|
| Return the address of the local endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockopt(self, level, option, buffersize=None)
| getsockopt(level, option[, buffersize]) -> value
|
| Get a socket option. See the Unix manual for level and option.
| If a nonzero buffersize argument is given, the return value is a
| string of that length; otherwise it is an integer.
|
| gettimeout(self)
| gettimeout() -> timeout
|
| Returns the timeout in seconds (float) associated with socket
| operations. A timeout of None indicates that timeouts on socket
| operations are disabled.
|
| ioctl(self, cmd, option)
| ioctl(cmd, option) -> long
|
| Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are
| SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.
| SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).
|
| listen(self, backlog)
| listen(backlog)
|
| Enable a server to accept connections. The backlog argument must be at
| least 0 (if it is lower, it is set to 0); it specifies the number of
| unaccepted connections that the system will allow before refusing new
| connections.
|
| recv(self, buffersize, flags=None)
| recv(buffersize[, flags]) -> data
|
| Receive up to buffersize bytes from the socket. For the optional flags
| argument, see the Unix manual. When no data is available, block until
| at least one byte is available or until the remote end is closed. When
| the remote end is closed and all data is read, return the empty string.
|
| recv_into(self, buffer, nbytes=None, flags=None)
| recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
|
| A version of recv() that stores its data into a buffer rather than creating
| a new string. Receive up to buffersize bytes from the socket. If buffersize
| is not specified (or 0), receive up to the size available in the given buffer.
|
| See recv() for documentation about the flags.
|
| recvfrom(self, buffersize, flags=None)
| recvfrom(buffersize[, flags]) -> (data, address info)
|
| Like recv(buffersize, flags) but also return the sender's address info.
|
| recvfrom_into(self, buffer, nbytes=None, flags=None)
| recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
|
| Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
|
| send(self, data, flags=None)
| send(data[, flags]) -> count
|
| Send a data string to the socket. For the optional flags
| argument, see the Unix manual. Return the number of bytes
| sent; this may be less than len(data) if the network is busy.
|
| sendall(self, data, flags=None)
| sendall(data[, flags])
|
| Send a data string to the socket. For the optional flags
| argument, see the Unix manual. This calls send() repeatedly
| until all data is sent. If an error occurs, it's impossible
| to tell how much data has been sent.
|
| sendto(self, data, flags=None, *args, **kwargs)
| sendto(data[, flags], address) -> count
|
| Like send(data, flags) but allows specifying the destination address.
| For IP sockets, the address is a pair (hostaddr, port).
|
| setblocking(self, flag)
| setblocking(flag)
|
| Set the socket to blocking (flag is true) or non-blocking (false).
| setblocking(True) is equivalent to settimeout(None);
| setblocking(False) is equivalent to settimeout(0.0).
|
| setsockopt(self, level, option, value)
| setsockopt(level, option, value)
|
| Set a socket option. See the Unix manual for level and option.
| The value argument can either be an integer or a string.
|
| settimeout(self, timeout)
| settimeout(timeout)
|
| Set a timeout on socket operations. 'timeout' can be a float,
| giving in seconds, or None. Setting a timeout of None disables
| the timeout feature and is equivalent to setblocking(1).
| Setting a timeout of zero is the same as setblocking(0).
|
| shutdown(self, flag)
| shutdown(flag)
|
| Shut down the reading side of the socket (flag == SHUT_RD), the writing side
| of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).

【学习笔记:Python-网络编程】Socket 之初见的更多相关文章

  1. python 3.x 学习笔记13 (网络编程socket)

    1.协议http.smtp.dns.ftp.ssh.snmp.icmp.dhcp....等具体自查 2.OSI七层应用.表示.会话.传输.网络.数据链路.物理 3.socket: 对所有上层协议的封装 ...

  2. Python网络编程socket

    网络编程之socket 看到本篇文章的题目是不是很疑惑,what is this?,不要着急,但是记住一说网络编程,你就想socket,socket是实现网络编程的工具,那么什么是socket,什么是 ...

  3. Day07 - Python 网络编程 Socket

    1. Python 网络编程 Python 提供了两个级别访问网络服务: 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口 ...

  4. python学习笔记11 ----网络编程

    网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...

  5. python学习笔记10 ----网络编程

    网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...

  6. python网络编程-socket编程

     一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...

  7. python网络编程socket /socketserver

    提起网络编程,不同于web编程,它主要是C/S架构,也就是服务器.客户端结构的.对于初学者而言,最需要理解的不是网络的概念,而是python对于网络编程都提供了些什么模块和功能.不同于计算机发展的初级 ...

  8. Python网络编程-Socket简单通信(及python实现远程文件发送)

    学习python中使用python进行网络编程,编写简单的客户端和服务器端进行通信,大部分内容来源于网络教程,这里进行总结供以后查阅. 先介绍下TCP的三次握手: 1,简单的发送消息: 服务器端: i ...

  9. Day10 Python网络编程 Socket编程

    一.客户端/服务器架构 1.C/S架构,包括: 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务)[QQ,SSH,MySQL,FTP] 2.C/S架构与socket的关系: 我们学习soc ...

  10. Python 网络编程——socket

    一 客户端/服务器架构 客户端(Client)服务器(Server)架构,即C/S架构,包括 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务) 理想/目标状态—— 最常用的软件服务器是 ...

随机推荐

  1. 22 Extends 继承(子类、父类)

    本章主要介绍继承的 概念.方法重写(@Override注解的使用).使用场景.方法的执行顺序 /*1.继承的 概念 * 继承:多个类有共同的成员变量和成员方法,抽取到另外一个类中(父类),在让多个类去 ...

  2. React Native简史

    诞生 React Native 诞生于 2013 年的 Facebook 内部黑客马拉松(hackathon): In the essence of Facebook’s hacker culture ...

  3. 记录:如何使用ASP.NET Core和EnityFramework Core实现服务和数据分离

    前情提要: 现有一个网站框架,包括主体项目WebApp一个,包含 IIdentityUser 接口的基架项目 A.用于处理用户身份验证的服务 AuthenticationService 位于命名空间B ...

  4. ajax按楼层加载数据

    代码如下: <!doctype html> <html> <head> <meta charset="utf-8"> <tit ...

  5. 杭电1080 J - Human Gene Functions

    题目大意: 两个字符串,可以再中间任何插入空格,然后让这两个串匹配,字符与字符之间的匹配有各自的分数,求最大分数 最长公共子序列模型. dp[i][j]表示当考虑吧串1的第i个字符和串2的第j个字符时 ...

  6. python列表简介

    什么是列表?如何使用列表?https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range 列表相关知识: ...

  7. Springboot:第一个Springboot程序(一)

    1.创建Springboot项目 选择创建Springboot项目: 填写项目基本信息: 选择Springboot版本以及web依赖(内嵌tomcat): 创建完成: 创建完成后 等待构建maven项 ...

  8. redis的多路复用是什么鬼

    有没有人和我一样, 自打知道了redis, 就一直听说什么redis单线程, 使用了多路复用等等. 天真的我以为多路复用是redis实现的技术. 今天才发现, 我被自己骗了, 多路复用是系统来实现的. ...

  9. 23-Java-Spring框架(一)

    一.Spring框架了解 Spring框架是一个开源的框架,为JavaEE应用提供多方面的解决方案,用于简化企业级应用的开发,相当于是一种容器,可以集成其他框架(结构图如下). 上图反映了框架引包的依 ...

  10. Python开发基础之Python常用的数据类型

    一.Python介绍 Python是一种动态解释型的编程语言.Python它简单易学.功能强大.支持面向对象.函数式编程,可以在Windows.Linux等多种操作系统上使用,同时Python可以在J ...