Python uses socket (socket) implement UDP and TCP communication O (≧ ▽ ≦) O Python Tips

Open Systems Interconnection model

The official model is divided into seven layers, but in actual use, most companies will put this model is divided into four or five layers.
Here Insert Picture Description
Establishing communication between a simple host in python, we need to know the IP, UDP and TCP

IP

Compared IP for most people are not familiar with what IP is, in Windows, we can ipconfigsee your IP and other related network configurations, while in linux we can ifconfigsee your IP and other related information
Windows environment ipconfig
Here Insert Picture Description
under Linux environment ifconfigHere Insert Picture Description
IP protocol, there are two, one is our current more commonly used IPv4 (inet), the other is still in the testing phase, but there are more and more places to start using IPv6 (inet6 ), because the IPv4 address bits to 32 bits (4 bytes) and November 26, 2019 was exhausted, so IPv6 address bits to 128 bits (16 bytes) as the next generation of IP addresses, has begun in life it can be seen everywhere. Click here Do you support IPv6 access

port

IP and port are inextricably linked, if you want to make a communication device, not only need to know each other's IP also need to know the other side of those open ports. Suppose we go to a friend's house, we can know each other's home address as the home of know each other, know each other's port numbers to know the other side of the door at the home where, if we just know each other's home, but can not find to the door, and the other we still can not communicate properly.
Port can be divided into two

  1. Port reserved system: 0 to 1023
  2. Dynamic Port: 1024 to 65535

We can not retain the port system to call, and in the port reserved for the system, we have to remember a few common port

  1. HTTP protocol ports: 80
  2. HTTPS protocol ports: 443

Sockets

Socket (socket): working directly in the application layer and the transport layer, the socket connector can be said that the application layer and the transport layer together. It is a convention computer directly communicate with each other. Almost all network programming language can support socket, Python is no exception. socket is one of Python's built-in modules, you can use without having to download

Method common properties socket

  1. Family (protocol family):
    1. AF_INET (IPv4)
    2. AF_INET6 (IPv6)
  2. type (socket type):
    1. SOCK_STREAM (TCP protocol)
    2. SOCK_DGRAM (UDP protocol)

UDP

UDP Features

  • And the other without having to establish a connection to send data
  • Can be one to one, one to many, many to many other models
  • Small system resources
    UDP is a data transmission mode, Python socket modules may be utilized for data transmission over UDP.
    UDP uses relatively simple process, and the server (the one serving) to distinguish between the client (the party being served) is not significant.
  1. Create socket
  2. Use the socket receive \ send data
  3. Closes the socket
    Here Insert Picture Description

UDP sends data

The default transmit data only send ASCII coded data, and data must be sent byte type, so we can use the .encode()method of changing the byte codes used in the Windows system is gbk encoding, if you are using a Mac or PC Linux system, data transmitted using the distortion is not utf-8

import socket

def send_main():
    # family(协议族):AF_INET(IPv4) AF_INET6(IPv6) type(套接字类型) SOCK_STREAM(TCP协议) SOCK_DGRAM(UDP协议)
    udp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    # 使用.sendto方法向指定ip的端口发送数据
    send_data = '数据'
    udp_socket.sendto(send_data.encode('gbk'), ('127.0.0.1', 12821))
    # 关闭UDP
    udp_socket.close()

if __name__ == '__main__':
    send_main()

Receiving UDP data

Receiving data, we need to use .bind()a method to bind an address, .recvfromthe maximum number of bytes and the method of receiving data receiving settings (default: 1024)
.bind()Method: the need to pass a tuple entry into ip and port, the port number tuple You need to type int. ip may be empty, when ip is empty, it will default to the local ip. Example `udp_socket.bind (( '', 1024 ))

def rece_main():
    udp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    udp_socket.bind(('', 12822))
    print(udp_socket.recvfrom(1024))

Using the .recvfrom()method of receiving a data array format :( byte data (the IP transmission, transmit port)).
Such as: (b '\ xca \ xfd \ xbe \ xdd', ( '127.0.0.1', 12821)), we can remove the byte used in which the .decode()method of conversion.

TCP

TCP Features

  • Connection-oriented

    • Communicating parties must establish a connection to the data transmission
    • Reliable transport
  • TCP uses to send response mechanism

    • Retransmission timeout
    • Error checking
    • Flow control and congestion management

TCP has a more obvious differences in the client and server
Here Insert Picture Description

TCP Client

type (socket type) TCP when creating the socket, used for SOCK_STREAM.

  1. Using the .connect()method of connecting the server
  2. Using the .send()transmission method of the data, .recv()a method of receiving data, the default maximum receiving 1024 bytes ( .encode()a method for setting a binary coding format, default format does not support Chinese ascll)
  3. Using the .close()method Disconnect
def tcp_send_client():
    """使用tcp发送数据"""
    # 创建tcp套接字
    tcp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    # 连接服务器
    tcp_socket.connect(('127.0.0.1', 12823))
    # 发送数据
    data = '数据'
    tcp_socket.send(data.encode('gbk'))
    # 断开连接
    tcp_socket.close()


def tcp_recv_client():
    """使用tcp接收数据"""
    # 创建TCP套接字
    tcp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    # 连接服务器
    tcp_socket.connect(('127.0.0.1', 12823))
    # 接收数据
    data = tcp_socket.recv(1024)
    # 打印数据
    print(data.decode('gbk'))
    # 断开连接
    tcp_socket.close()

TCP server

The main method used by the server

  1. .bind()Method binding port
  2. .listen()The method of passive into active (as will be appreciated answer mode is set, the incoming process value will affect the number of host connections simultaneously, while the number of simultaneous connections can also be affected by the system)
  3. .accept()Method, create a copy of the connection, and returns the information to connect the host (TCP UDP can be different from one to many, TCP connection can only be one way, but here the use of a solution that allows multiple host connections simultaneously, each times a TCP connection time will create a copy of a copy of the connection point, so that you can perform multiple connections)
  4. .recv()And .send()the need for receiving data and sending data method .accept()to operate a copy of the created socket operation if the direct socket method to create unpredictable errors occur
def tcp_recv_server():
    """服务端接收数据"""
    # 创建tcp套接字
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定信息
    tcp_server.bind(('127.0.0.1', 12824))
    # 将主动转被动(服务器提供连接服务时需要)
    tcp_server.listen(128)
    # 等待连接(接到连接后,会创建一个连接副本,然后返回连接到此端口的主机信息)
    new_tcp, host_info = tcp_server.accept()
    # 接收数据
    data = new_tcp.recv(1024).decode('gbk')
    print(data)


def tcp_send_server():
    """服务端发送数据"""
    # 创建tcp套接字
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定信息
    tcp_server.bind(('127.0.0.1', 12824))
    # 将主动转被动(服务器提供连接服务时需要)
    tcp_server.listen(128)
    # 等待连接(接到连接后,会创建一个连接副本,然后返回连接到此端口的主机信息)
    new_tcp, host_info = tcp_server.accept()
    # 发送数据
    data = 'TCP数据'
    new_tcp.send(data.encode('gbk'))

Difference between TCP and UDP

  • TCP connection-oriented; the UDP is connectionless, i.e. without establishing a connection before sending data.
  • TCP provides reliable service. In other words, the data transfer connection of TCP, error-free, not lost, not repeat, and arrive out of order; UDP best effort, that does not guarantee reliable delivery.
  • UDP has better real-time, high work efficiency than TCP, suitable for high-speed transmission and real-time communications have a higher or broadcast communications.
  • Each TCP connection can only point to point; UDP support one to one, one to many, and many-to-many interactive communication.
  • TCP more demanding on system resources, UDP less demanding on system resources.
  • TCP's customer service side and server-side difference was larger than UDP client and server difference
Published 47 original articles · won praise 23 · views 3402

Guess you like

Origin blog.csdn.net/qq_39611230/article/details/103942314