python socket模塊


  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中,發送多少,接收多少就是多少,不會講數據進行分塊,是將數據作為一個包發送,至於客戶端能接收到多少數據是不管的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM