python socket模块

2018-06-18 00:41:14来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

  1 import socket  # module
  2 import threading
  3 import time
  4 
  5 """
  6 FUNCTIONS
  7     create_connection(address, timeout=<object object at 0x000000000059D120>, source_address=None)
  8         Connect to *address* and return the socket object.
  9 
 10         Convenience function.  Connect to *address* (a 2-tuple ``(host,
 11         port)``) and return the socket object.  Passing the optional
 12         *timeout* parameter will set the timeout on the socket instance
 13         before attempting to connect.  If no *timeout* is supplied, the
 14         global default timeout setting returned by :func:`getdefaulttimeout`
 15         is used.  If *source_address* is set it must be a tuple of (host, port)
 16         for the socket to bind as a source address before making the connection.
 17         A host of '' or port 0 tells the OS to use the default.
 18 
 19     dup(...)
 20         dup(integer) -> integer
 21 
 22         Duplicate an integer socket file descriptor.  This is like os.dup(), but for
 23         sockets; on some platforms os.dup() won't work for socket file descriptors.
 24 
 25     fromfd(fd, family, type, proto=0)
 26         fromfd(fd, family, type[, proto]) -> socket object
 27 
 28         Create a socket object from a duplicate of the given file
 29         descriptor.  The remaining arguments are the same as for socket().
 30 
 31     fromshare(info)
 32         fromshare(info) -> socket object
 33 
 34         Create a socket object from the bytes object returned by
 35         socket.share(pid).
 36 
 37     getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
 38         Resolve host and port into list of address info entries.
 39 
 40         Translate the host/port argument into a sequence of 5-tuples that contain
 41         all the necessary arguments for creating a socket connected to that service.
 42         host is a domain name, a string representation of an IPv4/v6 address or
 43         None. port is a string service name such as 'http', a numeric port number or
 44         None. By passing None as the value of host and port, you can pass NULL to
 45         the underlying C API.
 46 
 47         The family, type and proto arguments can be optionally specified in order to
 48         narrow the list of addresses returned. Passing zero as a value for each of
 49         these arguments selects the full range of results.
 50 
 51     getdefaulttimeout(...)
 52         getdefaulttimeout() -> timeout
 53 
 54         Returns the default timeout in seconds (float) for new socket objects.
 55         A value of None indicates that new socket objects have no timeout.
 56         When the socket module is first imported, the default is None.
 57 
 58     getfqdn(name='')
 59         Get fully qualified domain name from name.
 60 
 61         An empty argument is interpreted as meaning the local host.
 62 
 63         First the hostname returned by gethostbyaddr() is checked, then
 64         possibly existing aliases. In case no FQDN is available, hostname
 65         from gethostname() is returned.
 66 
 67     gethostbyaddr(...)
 68         gethostbyaddr(host) -> (name, aliaslist, addresslist)
 69 
 70         Return the true host name, a list of aliases, and a list of IP addresses,
 71         for a host.  The host argument is a string giving a host name or IP number.
 72 
 73     gethostbyname(...)
 74         gethostbyname(host) -> address
 75 
 76         Return the IP address (a string of the form '255.255.255.255') for a host.
 77 
 78     gethostbyname_ex(...)
 79         gethostbyname_ex(host) -> (name, aliaslist, addresslist)
 80 
 81         Return the true host name, a list of aliases, and a list of IP addresses,
 82         for a host.  The host argument is a string giving a host name or IP number.
 83 
 84     gethostname(...)
 85         gethostname() -> string
 86 
 87         Return the current host name.
 88 
 89     getnameinfo(...)
 90         getnameinfo(sockaddr, flags) --> (host, port)
 91 
 92         Get host and port for a sockaddr.
 93 
 94     getprotobyname(...)
 95         getprotobyname(name) -> integer
 96 
 97         Return the protocol number for the named protocol.  (Rarely used.)
 98 
 99     getservbyname(...)
100         getservbyname(servicename[, protocolname]) -> integer
101 
102         Return a port number from a service name and protocol name.
103         The optional protocol name, if given, should be 'tcp' or 'udp',
104         otherwise any protocol will match.
105 
106     getservbyport(...)
107         getservbyport(port[, protocolname]) -> string
108 
109         Return the service name from a port number and protocol name.
110         The optional protocol name, if given, should be 'tcp' or 'udp',
111         otherwise any protocol will match.
112 
113     htonl(...)
114         htonl(integer) -> integer
115 
116         Convert a 32-bit integer from host to network byte order.
117 
118     htons(...)
119         htons(integer) -> integer
120 
121         Convert a 16-bit integer from host to network byte order.
122 
123     inet_aton(...)
124         inet_aton(string) -> bytes giving packed 32-bit IP representation
125 
126         Convert an IP address in string format (123.45.67.89) to the 32-bit packed
127         binary format used in low-level network functions.
128 
129     inet_ntoa(...)
130         inet_ntoa(packed_ip) -> ip_address_string
131 
132         Convert an IP address from 32-bit packed binary format to string format
133 
134     inet_ntop(...)
135         inet_ntop(af, packed_ip) -> string formatted IP address
136 
137         Convert a packed IP address of the given family to string format.
138 
139     inet_pton(...)
140         inet_pton(af, ip) -> packed IP address string
141 
142         Convert an IP address from string format to a packed string suitable
143         for use with low-level network functions.
144 
145     ntohl(...)
146         ntohl(integer) -> integer
147 
148         Convert a 32-bit integer from network to host byte order.
149 
150     ntohs(...)
151         ntohs(integer) -> integer
152 
153         Convert a 16-bit integer from network to host byte order.
154 
155     setdefaulttimeout(...)
156         setdefaulttimeout(timeout)
157 
158         Set the default timeout in seconds (float) for new socket objects.
159         A value of None indicates that new socket objects have no timeout.
160         When the socket module is first imported, the default is None.
161 
162     socketpair(family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, proto=0)
163         socketpair([family[, type[, proto]]]) -> (socket object, socket object)
164         Create a pair of socket objects from the sockets returned by the platform
165         socketpair() function.
166         The arguments are the same as for socket() except the default family is AF_UNIX
167         if defined on the platform; otherwise, the default is AF_INET.
168 """
169 
170 # 1、socket类方法
171 """
172     class socket(_socket.socket)
173      |  accept(self)
174      |      accept() -> (socket object, address info)
175      |      
176      |      Wait for an incoming connection.  Return a new socket
177      |      representing the connection, and the address of the client.
178      |      For IP sockets, the address info is a pair (hostaddr, port).
179      |      接受连接请求,返回新的描述符和客户端地址,tcp服务端使用
180      |     
181      |  close(self)
182      |      close()
183      |      
184      |      Close the socket.  It cannot be used after this call.
185      |  
186      |  detach(self)
187      |      detach() -> file descriptor
188      |      
189      |      Close the socket object without closing the underlying file descriptor.
190      |      The object cannot be used after this call, but the file descriptor
191      |      can be reused for other purposes.  The file descriptor is returned.
192      |      关闭socket对象,但不关闭底层的文件描述符
193      |      这个socket对象不能够再恢复了,但是这个文件描述符可以另做他用
194      |      返回这个文件描述符
195      |
196      |  dup(self)
197      |      dup() -> socket object
198      |      
199      |      Duplicate the socket. Return a new socket object connected to the same
200      |      system resource. The new socket is non-inheritable.
201      |      复制这个socket对象
202      |      返回一个新的sonket对象连接相同的系统资源
203      |      这个新的socket对象是不可以继承的
204      |
205      |  get_inheritable(self)
206      |      Get the inheritable flag of the socket
207      |  
208      |  makefile(self, mode='r', buffering=None, *, encoding=None, errors=None, newline=None)
209      |      makefile(...) -> an I/O stream connected to the socket
210      |      
211      |      The arguments are as for io.open() after the filename, except the only
212      |      supported mode values are 'r' (default), 'w' and 'b'.
213      |  
214      |  sendfile(self, file, offset=0, count=None)
215      |      sendfile(file[, offset[, count]]) -> sent
216      |      
217      |      Send a file until EOF is reached by using high-performance
218      |      os.sendfile() and return the total number of bytes which
219      |      were sent.
220      |      *file* must be a regular file object opened in binary mode.
221      |      If os.sendfile() is not available (e.g. Windows) or file is
222      |      not a regular file socket.send() will be used instead.
223      |      *offset* tells from where to start reading the file.
224      |      If specified, *count* is the total number of bytes to transmit
225      |      as opposed to sending the file until EOF is reached.
226      |      File position is updated on return or also in case of error in
227      |      which case file.tell() can be used to figure out the number of
228      |      bytes which were sent.
229      |      The socket must be of SOCK_STREAM type.
230      |      Non-blocking sockets are not supported.
231      |  
232      |  set_inheritable(self, inheritable)
233      |      Set the inheritable flag of the socket
234      |  
235      |  ----------------------------------------------------------------------
236      |  Methods inherited from _socket.socket:
237      |   
238      |  bind(...)
239      |      bind(address)
240      |      
241      |      Bind the socket to a local address.  For IP sockets, the address is a
242      |      pair (host, port); the host must refer to the local host. For raw packet
243      |      sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
244      |      绑定一个本地地址,addr=(host, port),服务端使用
245      |
246      |  connect(...)
247      |      connect(address)
248      |      
249      |      Connect the socket to a remote address.  For IP sockets, the address
250      |      is a pair (host, port).
251      |      连接到远程的addr,tcp客户端使用
252      |
253      |  connect_ex(...)
254      |      connect_ex(address) -> errno
255      |      
256      |      This is like connect(address), but returns an error code (the errno value)
257      |      instead of raising an exception when an error occurs.
258      |      同connect,不抛出异常,返回异常码
259      |  
260      |  fileno(...)
261      |      fileno() -> integer
262      |      
263      |      Return the integer file descriptor of the socket.
264      |      底层的文件描述符
265      |
266      |  getpeername(...)
267      |      getpeername() -> address info
268      |      
269      |      Return the address of the remote endpoint.  For IP sockets, the address
270      |      info is a pair (hostaddr, port).
271      |      查看远程地址,tcp使用,因为udp不发生连接,按照地址直接发送
272      |
273      |  getsockname(...)
274      |      getsockname() -> address info
275      |      
276      |      Return the address of the local endpoint.  For IP sockets, the address
277      |      info is a pair (hostaddr, port).
278      |      查看本地地址
279      |
280      |  getsockopt(...)
281      |      getsockopt(level, option[, buffersize]) -> value
282      |      
283      |      Get a socket option.  See the Unix manual for level and option.
284      |      If a nonzero buffersize argument is given, the return value is a
285      |      string of that length; otherwise it is an integer.
286      |  
287      |  gettimeout(...)
288      |      gettimeout() -> timeout
289      |      
290      |      Returns the timeout in seconds (float) associated with socket 
291      |      operations. A timeout of None indicates that timeouts on socket 
292      |      operations are disabled.
293      |  
294      |  ioctl(...)
295      |      ioctl(cmd, option) -> long
296      |      
297      |      Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are
298      |      SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.
299      |      SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).
300      |      SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default
301      |  
302      |  listen(...)
303      |      listen([backlog])
304      |      
305      |      Enable a server to accept connections.  If backlog is specified, it must be
306      |      at least 0 (if it is lower, it is set to 0); it specifies the number of
307      |      unaccepted connections that the system will allow before refusing new
308      |      connections. If not specified, a default reasonable value is chosen.
309      |      开始监听,tcp服务端使用
310      |
311      |  recv(...)
312      |      recv(buffersize[, flags]) -> data
313      |      
314      |      Receive up to buffersize bytes from the socket.  For the optional flags
315      |      argument, see the Unix manual.  When no data is available, block until
316      |      at least one byte is available or until the remote end is closed.  When
317      |      the remote end is closed and all data is read, return the empty string.
318      |      返回读到的数据
319      |      从socket对象中读取buflen大小的数据
320      |      没有数据的时候阻塞
321      |      远程关闭的时候,返回empty string
322      |      tcp使用,连接之后,通信不需要用到地址
323      |
324      |  recv_into(...)
325      |      recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
326      |      
327      |      A version of recv() that stores its data into a buffer rather than creating 
328      |      a new string.  Receive up to buffersize bytes from the socket.  If buffersize 
329      |      is not specified (or 0), receive up to the size available in the given buffer.
330      |      
331      |      See recv() for documentation about the flags.
332      |      返回读到的字节数
333      |      从socket对象中读取nbytes大小的数据,当nbytes没有指定或者为零,nbytes=bufferlen
334      |
335      |  recvfrom(...)
336      |      recvfrom(buffersize[, flags]) -> (data, address info)
337      |      
338      |      Like recv(buffersize, flags) but also return the sender's address info.
339      |      返回数据和发送数据方的地址,(data, address info)
340      |      其他同recv
341      |      udp使用,每次发送数据的时候要指定地址
342      |
343      |  recvfrom_into(...)
344      |      recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
345      |      
346      |      Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
347      |      返回(nbytes, address info)
348      |      其他同recv_into
349      |
350      |  send(...)
351      |      send(data[, flags]) -> count
352      |      
353      |      Send a data string to the socket.  For the optional flags
354      |      argument, see the Unix manual.  Return the number of bytes
355      |      sent; this may be less than len(data) if the network is busy.
356      |      返回发送的字节数量
357      |      如果网络忙的话发送的长度有可能小于len(data)
358      |      tcp使用
359      |
360      |  sendall(...)
361      |      sendall(data[, flags])
362      |      
363      |      Send a data string to the socket.  For the optional flags
364      |      argument, see the Unix manual.  This calls send() repeatedly
365      |      until all data is sent.  If an error occurs, it's impossible
366      |      to tell how much data has been sent.
367      |      重复调用send(),直到全部发送
368      |      如果出错,会告诉你已经发送了多少字节
369      |      tcp使用
370      |
371      |  sendto(...)
372      |      sendto(data[, flags], address) -> count
373      |      
374      |      Like send(data, flags) but allows specifying the destination address.
375      |      For IP sockets, the address is a pair (hostaddr, port).
376      |      返回发送的字节数量
377      |      可以指定地址
378      |      udp使用
379      |
380      |  setblocking(...)
381      |      setblocking(flag)
382      |      
383      |      Set the socket to blocking (flag is true) or non-blocking (false).
384      |      setblocking(True) is equivalent to settimeout(None);
385      |      setblocking(False) is equivalent to settimeout(0.0).
386      |  
387      |  setsockopt(...)
388      |      setsockopt(level, option, value: int)
389      |      setsockopt(level, option, value: buffer)
390      |      setsockopt(level, option, None, optlen: int)
391      |      
392      |      Set a socket option.  See the Unix manual for level and option.
393      |      The value argument can either be an integer, a string buffer, or 
394      |      None, optlen.
395      |  
396      |  settimeout(...)
397      |      settimeout(timeout)
398      |      
399      |      Set a timeout on socket operations.  'timeout' can be a float,
400      |      giving in seconds, or None.  Setting a timeout of None disables
401      |      the timeout feature and is equivalent to setblocking(1).
402      |      Setting a timeout of zero is the same as setblocking(0).
403      |  
404      |  share(...)
405      |      share(process_id) -> bytes
406      |      
407      |      Share the socket with another process.  The target process id
408      |      must be provided and the resulting bytes object passed to the target
409      |      process.  There the shared socket can be instantiated by calling
410      |      socket.fromshare().
411      |      进程间socket对象的共享
412      |  
413      |  shutdown(...)
414      |      shutdown(flag)
415      |      
416      |      Shut down the reading side of the socket (flag == SHUT_RD), the writing side
417      |      of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
418      |      关闭socket的读写功能
419 """
420 
421 
422 # 2、udp的通信
423 def udp_server():
424     # 1. 创建套接字
425     udp_fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
426 
427     # 2. 绑定本地的相关信息
428     bind_address = ('192.168.99.156', 7789)
429     udp_fd.bind(bind_address)
430 
431     while True:
432         # 3. 等待接收对方发送的数据
433         receive_data, receive_address = udp_fd.recvfrom(1024)
434         # 4. 将接收到的数据再发送给对方
435         udp_fd.sendto(receive_data, receive_address)
436         # 5. 统计信息
437         print('server: %s, %s' % (receive_data.decode(encoding='utf-8'), receive_address))
438 
439     #5. 关闭套接字
440     udp_fd.close()
441 
442 
443 def udp_client():
444     # 1. 创建套接字
445     udp_fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
446     # 2. 准备接收方的地址
447     send_address = ('192.168.99.156', 7789)
448     while True:
449         # 3. 从键盘获取数据
450         send_data = input("请输入要发送的数据:")
451         # 4. 发送数据到指定的电脑上
452         udp_fd.sendto(send_data.encode(encoding='utf-8'), send_address)
453         # 5、接收返回的信息
454         receive_data, receive_address = udp_fd.recvfrom(1024)
455         print('client: %s, %s' % (receive_data.decode(encoding='utf-8'), receive_address))
456     # 6. 关闭套接字
457     udp_fd.close()
458 
459 
460 t1 = threading.Thread(target=udp_server)
461 t2 = threading.Thread(target=udp_client)
462 t1.start()
463 t2.start()
464 t1.join()
465 t2.join()
466 
467 
468 # 3、tcp的通信
469 def tcp_server():
470     # 1、创建套接字
471     tcp_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
472     # 2、绑定本地信息
473     address = ('192.168.99.156', 7788)
474     tcp_fd.bind(address)
475     # 3、使用socket创建的套接字默认的属性是主动的,使用listen将其变为被动的,这样就可以接收别人的链接了
476     tcp_fd.listen(5)
477 
478     while True:
479         # 4、如果有新的客户端来链接服务器,那么就产生一个新的套接字专门为这个客户端服务器
480         # newSocket用来为这个客户端服务
481         # tcpSerSocket就可以省下来专门等待其他新客户端的链接
482         new_fd, client_address = tcp_fd.accept()
483         # 5、接收对方发送过来的数据,最大接收1024个字节
484         receive_data = new_fd.recv(1024)
485         print('server: 接收到的数据为:', receive_data.decode(encoding='utf-8'))
486         # 6、发送一些数据到客户端
487         new_fd.send(b"thank you !")
488         # print(new_fd.getpeername())
489         # print(new_fd.getsockname())
490         # 7、关闭为这个客户端服务的套接字,只要关闭了,就意味着为不能再为这个客户端服务了,如果还需要服务,只能再次重新连接
491         new_fd.close()
492 
493     # 关闭监听套接字,只要这个套接字关闭了,就意味着整个程序不能再接收任何新的客户端的连接
494     tcp_fd.close()
495 
496 
497 def tcp_client(num):
498     # 1、创建socket
499     tcp_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
500     # 2、链接服务器
501     server_address = ('192.168.99.156', 7788)
502     tcp_fd.connect(server_address)
503     # 3、发送数据
504     tcp_fd.send(b'hello world.')
505     # 4、接收对方发送过来的数据,最大接收1024个字节
506     receive_data = tcp_fd.recv(1024)
507     print('client-%s接收到的数据为:' % num, receive_data.decode(encoding='utf-8'))
508     # 5、关闭套接字
509     # print(tcp_fd.getpeername())
510     # print(tcp_fd.getsockname())
511     tcp_fd.close()
512 
513 
514 t1 = threading.Thread(target=tcp_server)
515 t1.start()
516 th = []
517 for i in range(5):
518     t = threading.Thread(target=tcp_client, args=(i,))
519     t.start()
520     time.sleep(1)
521     th.append(t)
522 for t in th:
523     t.join()
524 
525 
526 # 4、tcp与udp的区别
527 # (1)、 tcp是面向连接的,而udp是无连接,
528 #     在服务器端的反应就是,tcp需要做很多的设置工作,例如要进行监听listen,然后监听之后,进行接收客户端的连接,
529 #     也就是accept,当接收到连接之后,传递过来的是客户端的socket对象,然后利用这个socket对象进行发送接收消息。
530 #     而在udp中,不需要设置这些,只要绑定了地址和端口即可,在接收数据之后,得到客户端的地址和端口,
531 #     然后服务器端的udp对象将信息发送到对应的地址。
532 # (2)、在传输数据的方面,tcp是安全的,会将大量的数据进行分块然后进行发送,不会造成数据丢失;
533 #     而在udp中,发送多少,接收多少就是多少,不会讲数据进行分块,是将数据作为一个包发送,至于客户端能接收到多少数据是不管的。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Day01——Python简介

下一篇:pymysql