Python socket编程 (转)
Socket
socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用【打开】【读写】【关闭】模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)
基本上,Socket 是任何一种计算机网络通讯中最基础的内容。例如当你在浏览器地址栏中输入 http://www.cnblogs.com/ 时,你会打开一个套接字,然后连接到 http://www.cnblogs.com/ 并读取响应的页面然后然后显示出来。而其他一些聊天客户端如 gtalk 和 skype 也是类似。任何网络通讯都是通过 Socket 来完成的。
Python 官方关于 Socket 的函数请看 http://docs.python.org/library/socket.html
socket和file的区别:
1、file模块是针对某个指定文件进行【打开】【读写】【关闭】
2、socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】
先来创建一个socket服务端吧
1 #coding:utf8 2 3 import socket 4 5 sk = socket.socket() 6 sk.bind(("127.0.0.1",8080)) 7 sk.listen(5) 8 9 conn,address = sk.accept() 10 sk.sendall(bytes("Hello world",encoding="utf-8"))
1 import socket 2 3 obj = socket.socket() 4 obj.connect(("127.0.0.1",8080)) 5 6 ret = str(obj.recv(1024),encoding="utf-8") 7 print(ret)
socket更多功能
1 def bind(self, address): # real signature unknown; restored from __doc__ 2 """ 3 bind(address) 4 5 Bind the socket to a local address. For IP sockets, the address is a 6 pair (host, port); the host must refer to the local host. For raw packet 7 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]]) 8 """ 9 '''将套接字绑定到本地地址。是一个IP套接字的地址对(主机、端口),主机必须参考本地主机。''' 10 pass 11 12 def close(self): # real signature unknown; restored from __doc__ 13 """ 14 close() 15 16 Close the socket. It cannot be used after this call. 17 """ 18 '''关闭socket''' 19 pass 20 21 def connect(self, address): # real signature unknown; restored from __doc__ 22 """ 23 connect(address) 24 25 Connect the socket to a remote address. For IP sockets, the address 26 is a pair (host, port). 27 """ 28 '''将套接字连接到远程地址。IP套接字的地址''' 29 pass 30 31 def connect_ex(self, address): # real signature unknown; restored from __doc__ 32 """ 33 connect_ex(address) -> errno 34 35 This is like connect(address), but returns an error code (the errno value) 36 instead of raising an exception when an error occurs. 37 """ 38 pass 39 40 def detach(self): # real signature unknown; restored from __doc__ 41 """ 42 detach() 43 44 Close the socket object without closing the underlying file descriptor. 45 The object cannot be used after this call, but the file descriptor 46 can be reused for other purposes. The file descriptor is returned. 47 """ 48 '''关闭套接字对象没有关闭底层的文件描述符。''' 49 pass 50 51 def fileno(self): # real signature unknown; restored from __doc__ 52 """ 53 fileno() -> integer 54 55 Return the integer file descriptor of the socket. 56 """ 57 '''返回整数的套接字的文件描述符。''' 58 return 0 59 60 def getpeername(self): # real signature unknown; restored from __doc__ 61 """ 62 getpeername() -> address info 63 64 Return the address of the remote endpoint. For IP sockets, the address 65 info is a pair (hostaddr, port). 66 """ 67 '''返回远程端点的地址。IP套接字的地址''' 68 pass 69 70 def getsockname(self): # real signature unknown; restored from __doc__ 71 """ 72 getsockname() -> address info 73 74 Return the address of the local endpoint. For IP sockets, the address 75 info is a pair (hostaddr, port). 76 """ 77 '''返回远程端点的地址。IP套接字的地址''' 78 pass 79 80 def getsockopt(self, level, option, buffersize=None): # real signature unknown; restored from __doc__ 81 """ 82 getsockopt(level, option[, buffersize]) -> value 83 84 Get a socket option. See the Unix manual for level and option. 85 If a nonzero buffersize argument is given, the return value is a 86 string of that length; otherwise it is an integer. 87 """ 88 '''得到一个套接字选项''' 89 pass 90 91 def gettimeout(self): # real signature unknown; restored from __doc__ 92 """ 93 gettimeout() -> timeout 94 95 Returns the timeout in seconds (float) associated with socket 96 operations. A timeout of None indicates that timeouts on socket 97 operations are disabled. 98 """ 99 '''返回的超时秒数(浮动)与套接字相关联''' 100 return timeout 101 102 def ioctl(self, cmd, option): # real signature unknown; restored from __doc__ 103 """ 104 ioctl(cmd, option) -> long 105 106 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are 107 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants. 108 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval). 109 """ 110 return 0 111 112 def listen(self, backlog=None): # real signature unknown; restored from __doc__ 113 """ 114 listen([backlog]) 115 116 Enable a server to accept connections. If backlog is specified, it must be 117 at least 0 (if it is lower, it is set to 0); it specifies the number of 118 unaccepted connections that the system will allow before refusing new 119 connections. If not specified, a default reasonable value is chosen. 120 """ 121 '''使服务器能够接受连接。''' 122 pass 123 124 def recv(self, buffersize, flags=None): # real signature unknown; restored from __doc__ 125 """ 126 recv(buffersize[, flags]) -> data 127 128 Receive up to buffersize bytes from the socket. For the optional flags 129 argument, see the Unix manual. When no data is available, block until 130 at least one byte is available or until the remote end is closed. When 131 the remote end is closed and all data is read, return the empty string. 132 """ 133 '''当没有数据可用,阻塞,直到至少一个字节是可用的或远程结束之前关闭。''' 134 pass 135 136 def recvfrom(self, buffersize, flags=None): # real signature unknown; restored from __doc__ 137 """ 138 recvfrom(buffersize[, flags]) -> (data, address info) 139 140 Like recv(buffersize, flags) but also return the sender's address info. 141 """ 142 pass 143 144 def recvfrom_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__ 145 """ 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 pass 151 152 def recv_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__ 153 """ 154 recv_into(buffer, [nbytes[, flags]]) -> nbytes_read 155 156 A version of recv() that stores its data into a buffer rather than creating 157 a new string. Receive up to buffersize bytes from the socket. If buffersize 158 is not specified (or 0), receive up to the size available in the given buffer. 159 160 See recv() for documentation about the flags. 161 """ 162 pass 163 164 def send(self, data, flags=None): # real signature unknown; restored from __doc__ 165 """ 166 send(data[, flags]) -> count 167 168 Send a data string to the socket. For the optional flags 169 argument, see the Unix manual. Return the number of bytes 170 sent; this may be less than len(data) if the network is busy. 171 """ 172 '''发送一个数据字符串到套接字。''' 173 pass 174 175 def sendall(self, data, flags=None): # real signature unknown; restored from __doc__ 176 """ 177 sendall(data[, flags]) 178 179 Send a data string to the socket. For the optional flags 180 argument, see the Unix manual. This calls send() repeatedly 181 until all data is sent. If an error occurs, it's impossible 182 to tell how much data has been sent. 183 """ 184 '''发送一个数据字符串到套接字,直到所有数据发送完成''' 185 pass 186 187 def sendto(self, data, flags=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 188 """ 189 sendto(data[, flags], address) -> count 190 191 Like send(data, flags) but allows specifying the destination address. 192 For IP sockets, the address is a pair (hostaddr, port). 193 """ 194 pass 195 196 def setblocking(self, flag): # real signature unknown; restored from __doc__ 197 """ 198 setblocking(flag) 199 200 Set the socket to blocking (flag is true) or non-blocking (false). 201 setblocking(True) is equivalent to settimeout(None); 202 setblocking(False) is equivalent to settimeout(0.0). 203 """ 204 '''是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。''' 205 pass 206 207 def setsockopt(self, level, option, value): # real signature unknown; restored from __doc__ 208 """ 209 setsockopt(level, option, value) 210 211 Set a socket option. See the Unix manual for level and option. 212 The value argument can either be an integer or a string. 213 """ 214 pass 215 216 def settimeout(self, timeout): # real signature unknown; restored from __doc__ 217 """ 218 settimeout(timeout) 219 220 Set a timeout on socket operations. 'timeout' can be a float, 221 giving in seconds, or None. Setting a timeout of None disables 222 the timeout feature and is equivalent to setblocking(1). 223 Setting a timeout of zero is the same as setblocking(0). 224 """ 225 pass 226 227 def share(self, process_id): # real signature unknown; restored from __doc__ 228 """ 229 share(process_id) -> bytes 230 231 Share the socket with another process. The target process id 232 must be provided and the resulting bytes object passed to the target 233 process. There the shared socket can be instantiated by calling 234 socket.fromshare(). 235 """ 236 return b"" 237 238 def shutdown(self, flag): # real signature unknown; restored from __doc__ 239 """ 240 shutdown(flag) 241 242 Shut down the reading side of the socket (flag == SHUT_RD), the writing side 243 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR). 244 """ 245 pass 246 247 def _accept(self): # real signature unknown; restored from __doc__ 248 """ 249 _accept() -> (integer, address info) 250 251 Wait for an incoming connection. Return a new socket file descriptor 252 representing the connection, and the address of the client. 253 For IP sockets, the address info is a pair (hostaddr, port). 254 """ 255 pass 256
sk.bind(address)
s.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。
sk.listen(backlog)
开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。
backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
这个值不能无限大,因为要在内核中维护连接队列
sk.setblocking(bool)
是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。
sk.accept()
接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
接收TCP 客户的连接(阻塞式)等待连接的到来
sk.connect(address)
连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
sk.connect_ex(address)
同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061
sk.close()
关闭套接字
sk.recv(bufsize[,flag])
接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。
sk.recvfrom(bufsize[.flag])
与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。
sk.send(string[,flag])
将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。
sk.sendall(string[,flag])
将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。
内部通过递归调用send,将所有内容发送出去。
sk.sendto(string[,flag],address)
将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。
sk.settimeout(timeout)
设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
sk.getpeername()
返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
sk.getsockname()
返回套接字自己的地址。通常是一个元组(ipaddr,port)
sk.fileno()
套接字的文件描述符
TCP:
1 import socketserver 2 服务端 3 4 class Myserver(socketserver.BaseRequestHandler): 5 6 def handle(self): 7 8 conn = self.request 9 conn.sendall(bytes("你好,我是机器人",encoding="utf-8")) 10 while True: 11 ret_bytes = conn.recv(1024) 12 ret_str = str(ret_bytes,encoding="utf-8") 13 if ret_str == "q": 14 break 15 conn.sendall(bytes(ret_str+"你好我好大家好",encoding="utf-8")) 16 17 if __name__ == "__main__": 18 server = socketserver.ThreadingTCPServer(("127.0.0.1",8080),Myserver) 19 server.serve_forever() 20 21 客户端 22 23 import socket 24 25 obj = socket.socket() 26 27 obj.connect(("127.0.0.1",8080)) 28 29 ret_bytes = obj.recv(1024) 30 ret_str = str(ret_bytes,encoding="utf-8") 31 print(ret_str) 32 33 while True: 34 inp = input("你好请问您有什么问题? >>>") 35 if inp == "q": 36 obj.sendall(bytes(inp,encoding="utf-8")) 37 break 38 else: 39 obj.sendall(bytes(inp, encoding="utf-8")) 40 ret_bytes = obj.recv(1024) 41 ret_str = str(ret_bytes,encoding="utf-8") 42 print(ret_str)
1 服务端 2 3 import socket 4 5 sk = socket.socket() 6 7 sk.bind(("127.0.0.1",8080)) 8 sk.listen(5) 9 10 while True: 11 conn,address = sk.accept() 12 conn.sendall(bytes("欢迎光临我爱我家",encoding="utf-8")) 13 14 size = conn.recv(1024) 15 size_str = str(size,encoding="utf-8") 16 file_size = int(size_str) 17 18 conn.sendall(bytes("开始传送", encoding="utf-8")) 19 20 has_size = 0 21 f = open("db_new.jpg","wb") 22 while True: 23 if file_size == has_size: 24 break 25 date = conn.recv(1024) 26 f.write(date) 27 has_size += len(date) 28 29 f.close() 30 31 客户端 32 33 import socket 34 import os 35 36 obj = socket.socket() 37 38 obj.connect(("127.0.0.1",8080)) 39 40 ret_bytes = obj.recv(1024) 41 ret_str = str(ret_bytes,encoding="utf-8") 42 print(ret_str) 43 44 size = os.stat("yan.jpg").st_size 45 obj.sendall(bytes(str(size),encoding="utf-8")) 46 47 obj.recv(1024) 48 49 with open("yan.jpg","rb") as f: 50 for line in f: 51 obj.sendall(line)
UDP:
1 import socket 2 ip_port = ('127.0.0.1',9999) 3 sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0) 4 sk.bind(ip_port) 5 6 while True: 7 data = sk.recv(1024) 8 print data 9 10 11 12 13 import socket 14 ip_port = ('127.0.0.1',9999) 15 16 sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0) 17 while True: 18 inp = input('数据:').strip() 19 if inp == 'exit': 20 break 21 sk.sendto(bytes(inp,encoding = "utf-8"),ip_port) 22 23 sk.close() 24 25 udp传输
WEB服务应用:
1 #coding:utf-8 2 import socket 3 4 def handle_request(client): 5 buf = client.recv(1024) 6 client.send("HTTP/1.1 200 OK ") 7 client.send("Hello, World") 8 9 def main(): 10 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 sock.bind(('localhost',8080)) 12 sock.listen(5) 13 14 while True: 15 connection, address = sock.accept() 16 handle_request(connection) 17 connection.close() 18 19 if __name__ == '__main__': 20 main()