Python Network Programming -- socket and communication

Yongliang 2020-11-13 13:37:42
python network programming socket communication


1、socket Concept

​ Socket Is the application layer and TCP/IP Intermediate software abstraction layer for protocol family communication , It's a set of interfaces . In design mode ,Socket It's a facade pattern , It's complicated TCP/IP The protocol family is hidden in Socket The back of the interface , For users , A simple set of interfaces is all , Give Way Socket To organize data , To comply with the specified protocol .

img

 In fact, it can be considered that ,socket It's just a module . We establish the connection and communication between the two processes by calling the methods already implemented in the module .
Can also be socket Think it's ip+port, because ip It is used to identify the location of a host in the Internet , and port It's used to identify an application on this machine .
So we just need to establish ip and port You can find an application , And use socket Module to communicate with .

2、socket( Socket ) The development history and types of

Sockets originate 20 century 70 University of California, Berkeley version Unix, That's what people say BSD Unix. therefore , Sometimes people call sockets “ Berkeley socket ” or “BSD Socket ”. In the beginning, sockets were designed to be used with Communication between multiple applications on a host . This is also known as interprocess communication or IPC. There are two types of sockets ( Or there are two races , They are file based and network-based .

A family of sockets based on file types

The name of the socket family :AF_UNIX

unix Everything is a document , File-based sockets call on the underlying file system to fetch data , Two socket processes run on the same machine , Communication can be done indirectly by accessing the same file system .

Socket family based on network type

The name of the socket family :AF_INET

( also AF_INET6 Be used for ipv6, There are other address families , however , They are either used for a particular platform , Or it has been abandoned , Or it's rarely used , Or not at all , All address families ,AF_INET It's the most widely used one ,python Support many address families , But for network programming , Most of the time only use AF_INET)

3、TCP The protocol and UDP agreement

TCP(Transmission Control Protocol) reliable 、 Connection oriented protocol 、 Low transmission efficiency full duplex communication ( Send cache & Receive cache )、 Byte stream oriented . Use TCP Application :Web browser ; E-mail 、 File transfer program .

UDP(User Datagram Protocol) unreliable 、 Connectionless service , High transmission efficiency ( Little delay before sending ), one-on-one 、 One to many 、 For one more 、 Many to many 、 Message oriented , Do your best to serve , No congestion control . Use UDP Application : The domain name system (DNS); Video streaming ;IP voice (VoIP).

img

4、socket( Socket ) The early use of

(1)、 be based on TCP Agreed socket

<1>、 Server side

import socket
sk = socket.socket() # Creates a socket for the server
sk.bind(('127.0.0.1',9001)) # Bind an address IP + port
sk.listen() # Start listening for client requests
# 127.0.0.1 Always identify the local address
# But the switch You can get rid of some network problems in the process of writing code
conn,addr = sk.accept() # Receive a connection request
conn.send(b'hello') # Send messages to clients
msg = conn.recv(1024).decode('utf-8') # Receive client information , And limit the number of bytes received
print(msg)
conn.close() # End the message with the other party
sk.close() # Close the server socket

<2>、 client

import socket
sk = socket.socket() # Create a customer socket
sk.connect(('127.0.0.1',9001)) # Try to connect to the server IP + port
msg = sk.recv(23) # dialogue ( send out / receive )
print(msg)
sk.send(' Hello '.encode('utf-8'))
sk.close() # Close the client socket

Be careful :

​ TCP It's connection based , The server side must be started first , Then start the client to connect to the server .

​ UDP It's disconnected , After starting the service, you can accept the message directly , There's no need to set up a link in advance .

# When you restart the server, you may encounter errors
OSError: [Error 48] Address already in use
# terms of settlement : Join a socket To configure , reusing ip And port
import socket
from socket import SOL_SOCKET,SO_REUSEADDR
sk = socket.socket()
sk.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # Join this
sk.bind(('127.0.0.1',8898)) # Bind address to socket
···

(2)、 be based on UDP Agreed socket

<1>、 Server side

from socket import socket,SOCK_DGRAM
sk = socket(type=SOCK_DGRAM) # Creates a socket for the server
sk.bind(('127.0.0.1',9001)) # Bind the server socket
while True:
msg,cli_addr = sk.recvfrom(1024) # dialogue ( Receive and send )
print(msg.decode('utf-8'))
msg = input('>>>')
if msg.upper() == 'Q':continue
sk.sendto(msg.encode('utf-8'),cli_addr)

<2>、 client

from socket import socket,SOCK_DGRAM
sk = socket(type=SOCK_DGRAM)
server_addr = ('127.0.0.1',9001)
while True:
msg = input('>>>')
if msg.upper() == 'Q':
break
sk.sendto(msg.encode('utf-8'),server_addr)
msg = sk.recv(1024)
print(msg.decode('utf-8'))

5、socket Detailed explanation

socket.socket(family=AF_INET,type=SOCK_STREAM,proto=0,fileno=None)

<1>、 establish socket Parameter description of object :

family Address series should be AF_INET( The default value is ),AF_INET6,AF_UNIX,AF_CAN or AF_RDS. (AF_UNIX The domain actually uses local socket Files to communicate )
type Socket type should be SOCK_STREAM( The default value is ),SOCK_DGRAM,SOCK_RAW Or others SOCK_ One of the constants . SOCK_STREAM Is based on TCP Of , Guaranteed ( That is to ensure that the data is correctly transmitted to the other party ) Connection oriented SOCKET, For data transmission . SOCK_DGRAM Is based on UDP Of , Unprotected, message oriented socket, It is used to send broadcast information on the network .
proto The agreement number is usually zero , It can be omitted , Or in the address family AF_CAN Under the circumstances , The agreement shall be CAN_RAW or CAN_BCM One of .
fileno If you specify fileno, The other parameters are ignored , Causes the socket with the specified file descriptor to return . And socket.fromfd() Different ,fileno Will return the same socket , Instead of repeating . This may help to use socket.close() Turn off a separate outlet .

<2>、 socket More ways to introduce

# Server socket function
s.bind() # binding ( host , Port number ) To socket
s.listen() # Start TCP monitor
s.accept() # Passive acceptance TCP Customer connection ,( Blocking type ) Waiting for the connection
# Client socket functions
s.connect() # Active initialization TCP Server connection
s.connect_ex() # connect() Extended version of function , Error code returned when error , Instead of throwing an exception
# Socket functions for public use
s.recv() # receive TCP data
s.send() # send out TCP data
s.sendall() # send out TCP data
s.recvfrom() # receive UDP data
s.sendto() # send out UDP data
s.getpeername() # The address of the remote connection to the current socket
s.getsockname() # The address of the current socket
s.getsockopt() # Returns the parameters of the specified socket
s.setsockopt() # Set the parameters of the specified socket
s.close() # Close socket
# Lock oriented socket method
s.setblocking() # Set the blocking and non blocking mode of the socket
s.settimeout() # Set the timeout for blocking socket operations
s.gettimeout() # Get the timeout for blocking socket operations
# File oriented socket functions
s.fileno() # File descriptor for socket
s.makefile() # Create a file related to the socket
版权声明
本文为[Yongliang]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database