Socket 是任何一种计算机网络通讯中最基础的内容。当你在浏览器地址栏中输入一个地址时,你会打开一个套接字,可以说任何网络通讯都是通过 Socket 来完成的。
Socket 的 python 官方函数 http://docs.python.org/library/socket.html
socket和file的区别:
1、file模块是针对某个指定文件进行【打开】【读写】【关闭】
2、socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】
基本流程:
简单的一个端对端单线通信代码如下:
Server:
1 # -*- coding:utf-8 2 import socket 3 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 4 sock.bind(("0.0.0.0",12800)) 5 sock.listen(2) 6 while True: 7 conn,sockname = sock.accept() 8 print("Now,We have accepted a connection from:",sockname) 9 print("Socket Name is:",conn.getsockname()) 10 print("Socket Peer is:",conn.getpeername()) 11 message = conn.recv(1024) 12 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__
1 class SocketType(__builtin__.object) 2 | socket([family[, type[, proto]]]) -> socket object 3 | 4 | Open a socket of the given type. The family argument specifies the 5 | address family; it defaults to AF_INET. The type argument specifies 6 | whether this is a stream (SOCK_STREAM, this is the default) 7 | or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0, 8 | specifying the default protocol. Keyword arguments are accepted. 9 | 10 | A socket object represents one endpoint of a network connection. 11 | 12 | Methods of socket objects (keyword arguments not allowed): 13 | 14 | accept() -- accept a connection, returning new socket and client address 15 | bind(addr) -- bind the socket to a local address 16 | close() -- close the socket 17 | connect(addr) -- connect the socket to a remote address 18 | connect_ex(addr) -- connect, return an error code instead of an exception 19 | dup() -- return a new socket object identical to the current one [*] 20 | fileno() -- return underlying file descriptor 21 | getpeername() -- return remote address [*] 22 | getsockname() -- return local address 23 | getsockopt(level, optname[, buflen]) -- get socket options 24 | gettimeout() -- return timeout or None 25 | listen(n) -- start listening for incoming connections 26 | makefile([mode, [bufsize]]) -- return a file object for the socket [*] 27 | recv(buflen[, flags]) -- receive data 28 | recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer) 29 | recvfrom(buflen[, flags]) -- receive data and sender's address 30 | recvfrom_into(buffer[, nbytes, [, flags]) 31 | -- receive data and sender's address (into a buffer) 32 | sendall(data[, flags]) -- send all data 33 | send(data[, flags]) -- send data, may not send all of it 34 | sendto(data[, flags], addr) -- send data to a given address 35 | setblocking(0 | 1) -- set or clear the blocking I/O flag 36 | setsockopt(level, optname, value) -- set socket options 37 | settimeout(None | float) -- set or clear the timeout 38 | shutdown(how) -- shut down traffic in one or both directions 39 | 40 | [*] not available on all platforms! 41 | 42 | Methods defined here: 43 44 | 45 | accept(self) 46 | accept() -> (socket object, address info) 47 | 48 | Wait for an incoming connection. Return a new socket representing the 49 | connection, and the address of the client. For IP sockets, the address 50 | info is a pair (hostaddr, port). 51 | 52 | bind(self, address) 53 54 | bind(address) 55 | 56 | Bind the socket to a local address. For IP sockets, the address is a 57 | pair (host, port); the host must refer to the local host. For raw packet 58 | sockets the address is a tuple (ifname, proto [,pkttype [,hatype]]) 59 | 60 | close(self) 61 | close() 62 | 63 | Close the socket. It cannot be used after this call. 64 | 65 | connect(self, address) 66 | connect(address) 67 | 68 | Connect the socket to a remote address. For IP sockets, the address 69 | is a pair (host, port). 70 | 71 | connect_ex(self, address) 72 | connect_ex(address) -> errno 73 | 74 | This is like connect(address), but returns an error code (the errno value) 75 | instead of raising an exception when an error occurs. 76 | 77 | fileno(self) 78 | fileno() -> integer 79 | 80 | Return the integer file descriptor of the socket. 81 | 82 | getpeername(self) 83 | getpeername() -> address info 84 | 85 | Return the address of the remote endpoint. For IP sockets, the address 86 | info is a pair (hostaddr, port). 87 | 88 | getsockname(self) 89 | getsockname() -> address info 90 | 91 | Return the address of the local endpoint. For IP sockets, the address 92 | info is a pair (hostaddr, port). 93 | 94 | getsockopt(self, level, option, buffersize=None) 95 | getsockopt(level, option[, buffersize]) -> value 96 | 97 | Get a socket option. See the Unix manual for level and option. 98 | If a nonzero buffersize argument is given, the return value is a 99 | string of that length; otherwise it is an integer. 100 | 101 | gettimeout(self) 102 | gettimeout() -> timeout 103 | 104 | Returns the timeout in seconds (float) associated with socket 105 | operations. A timeout of None indicates that timeouts on socket 106 | operations are disabled. 107 | 108 | ioctl(self, cmd, option) 109 | ioctl(cmd, option) -> long 110 | 111 | Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are 112 | SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants. 113 | SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval). 114 | 115 | listen(self, backlog) 116 | listen(backlog) 117 | 118 | Enable a server to accept connections. The backlog argument must be at 119 | least 0 (if it is lower, it is set to 0); it specifies the number of 120 | unaccepted connections that the system will allow before refusing new 121 | connections. 122 | 123 | recv(self, buffersize, flags=None) 124 | recv(buffersize[, flags]) -> data 125 | 126 | Receive up to buffersize bytes from the socket. For the optional flags 127 | argument, see the Unix manual. When no data is available, block until 128 | at least one byte is available or until the remote end is closed. When 129 | the remote end is closed and all data is read, return the empty string. 130 | 131 | recv_into(self, buffer, nbytes=None, flags=None) 132 | recv_into(buffer, [nbytes[, flags]]) -> nbytes_read 133 | 134 | A version of recv() that stores its data into a buffer rather than creating 135 | a new string. Receive up to buffersize bytes from the socket. If buffersize 136 | is not specified (or 0), receive up to the size available in the given buffer. 137 | 138 | See recv() for documentation about the flags. 139 | 140 | recvfrom(self, buffersize, flags=None) 141 | recvfrom(buffersize[, flags]) -> (data, address info) 142 | 143 | Like recv(buffersize, flags) but also return the sender's address info. 144 | 145 | recvfrom_into(self, buffer, nbytes=None, flags=None) 146 | recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info) 147 | 148 | Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info. 149 | 150 | send(self, data, flags=None) 151 | send(data[, flags]) -> count 152 | 153 | Send a data string to the socket. For the optional flags 154 | argument, see the Unix manual. Return the number of bytes 155 | sent; this may be less than len(data) if the network is busy. 156 | 157 | sendall(self, data, flags=None) 158 | sendall(data[, flags]) 159 | 160 | Send a data string to the socket. For the optional flags 161 | argument, see the Unix manual. This calls send() repeatedly 162 | until all data is sent. If an error occurs, it's impossible 163 | to tell how much data has been sent. 164 | 165 | sendto(self, data, flags=None, *args, **kwargs) 166 | sendto(data[, flags], address) -> count 167 | 168 | Like send(data, flags) but allows specifying the destination address. 169 | For IP sockets, the address is a pair (hostaddr, port). 170 | 171 | setblocking(self, flag) 172 | setblocking(flag) 173 | 174 | Set the socket to blocking (flag is true) or non-blocking (false). 175 | setblocking(True) is equivalent to settimeout(None); 176 | setblocking(False) is equivalent to settimeout(0.0). 177 | 178 | setsockopt(self, level, option, value) 179 | setsockopt(level, option, value) 180 | 181 | Set a socket option. See the Unix manual for level and option. 182 | The value argument can either be an integer or a string. 183 | 184 | settimeout(self, timeout) 185 | settimeout(timeout) 186 | 187 | Set a timeout on socket operations. 'timeout' can be a float, 188 | giving in seconds, or None. Setting a timeout of None disables 189 | the timeout feature and is equivalent to setblocking(1). 190 | Setting a timeout of zero is the same as setblocking(0). 191 | 192 | shutdown(self, flag) 193 | shutdown(flag) 194 | 195 | Shut down the reading side of the socket (flag == SHUT_RD), the writing side 196 | of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR). 197