[socket communication] Python realizes simple socket communication | server and client

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

Reference content:
1) Introduction to Socket programming of TCP/IP network communication

1. Basic knowledge of socket communication

1.1 Basic knowledge

Socket is also known as socket. The basic information needed for socket startup: the host number and port number
for communication . (The port number actually represents the process, that is, which application program on the host will communicate) The socket is connected between two computers like a data line, serving as a communication bridge.

1.2 socket type

Socket generally has two types: TCP and UDP .
TCP: Transmission Control Protocol Transmission Control Protocol
TCP protocol is reliable , and the data sent will be received by the other party. TCP is a data stream-based protocol (data stream).
UDP: User Datagram Protocol User Datagram Protocol
UDP is unreliable , and it does not necessarily guarantee that the data will be received by the other party. UDP generally has lower latency and takes up less resources (suitable for voice calls)

The following content is based on the knowledge points of TCP and UDP captured by chatGPT :

TCP and UDP are two different network transport protocols. TCP (Transmission Control Protocol) is a connection-oriented protocol that establishes a reliable connection and then sends data over the connection. UDP (User Datagram Protocol) is a connectionless protocol that does not guarantee reliable transmission of data. The TCP protocol requires a three-way handshake before transmitting data. After the connection is established, the reliability of data transmission is high, but the transmission efficiency is low. The UDP protocol does not need to establish a connection, and the transmission efficiency is high, but the reliability of the data cannot be guaranteed.
The TCP protocol is suitable for scenarios that require reliable data transmission, such as email, file transfer, web browsing, etc. The UDP protocol is suitable for scenarios that require fast transmission, such as audio and video streaming.

Two, socket python implementation

2.1. Server code server.py

import socket

# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名和端口号
host = socket.gethostname()
port = 8888

# 将socket对象绑定到指定的主机和端口上
server_socket.bind((host, port))

# 开始监听连接
server_socket.listen(1)

# 等待客户端连接
print("等待客户端连接...")
client_socket, client_address = server_socket.accept()

print("连接来自: ", client_address)

# 接收客户端发送的数据
data = client_socket.recv(1024)

# 处理接收到的数据
print("接收到的数据为: ", data.decode())

# 发送响应数据给客户端
message = "欢迎连接到服务器!"
client_socket.send(message.encode())

# 关闭客户端连接
client_socket.close()

1) socket.gethostname() and socket.gethostbyname() are different:
socket.gethostname() obtains the hostname of the current host for use in the Socket connection. If you want to use an IP address instead of a host name for a Socket connection, you can use the socket.gethostbyname() function to get the host's IP address.
2) Regarding the port number
Once a socket object is bound to an IP address and port number through the socket.bind() method, the socket object will be assigned a unique port number. This port number can be used to send and receive data, so as to realize Socket communication.
When a client wants to connect to this server, the client needs to know the IP address and port number of the server. The client establishes a Socket connection through this port number and communicates with the server to realize data transmission and exchange. Therefore, the port number is a very important concept in Socket communication.
This port number is for this socket object.
3) server_socket.accept()
server_socket.accept() will block the program until a client connects. Once a client connects in, the accept() method will return a new socket object client_socket and the client's address information client_address.
The client can communicate with the client through the client_socket, and the client_address contains the client's IP address and port number, which can be used to identify the client's identity.

2.2. Client code client.py

import socket

# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取服务器的主机名和端口号
host = socket.gethostname()
port = 8888

# 连接到服务器
client_socket.connect((host, port))

# 发送消息给服务器
message = "Hello, 服务器!"
client_socket.send(message.encode())

# 接收服务器发送的响应数据
data = client_socket.recv(1024)

# 处理接收到的响应数据
print("接收到的数据为: ", data.decode())

# 关闭客户端连接
client_socket.close()

1) The difference with the server code:
Compared with the server code, the main difference of the client code is that it uses the socket.connect() method to connect to the server, and uses the socket.send() method to send messages to the server, while The server code uses the socket.bind() method to bind an IP address and port number, and uses the socket.listen() method to listen for client connection requests, and then uses the socket.accept() method to accept the client connection, and uses the socket. The recv() method receives messages sent by the client.
2) message.encode()
message.encode() is a method of strings in Python, which is used to encode strings into byte sequences. In Python, strings are stored in Unicode encoding, and byte sequences are often used to transmit data in network transmission, so strings need to be encoded into byte sequences before they can be transmitted on the network.
The message.encode() method encodes the string message into a byte sequence according to the default encoding method (usually UTF-8 encoding), and returns an object of type bytes. This bytes object can be directly transmitted to the send() method of the socket and sent to the network. At the receiving end, the received byte sequence needs to be decoded into a string using the corresponding decoding method ( such as the bytes.decode() method, which appeared in the server program ).

2.3. How to run

How to use: Use two terminal cmds to run two py files (server first and then client), and the final results are as follows:
server:
insert image description here

client:
insert image description here

The above code will definitely cause many problems for beginners
1) What should the port number of the client be set to?
In Socket communication, the port number is used to identify the server program or client program. In the server program, we need to specify a port number so that the client program can connect to the port for communication. Usually, we can choose some predefined port numbers, for example, the port number of the HTTP protocol is 80, the port number of the SMTP protocol is 25, and so on. However, we can also choose to customize the port number if the predefined port number is already taken or not suitable for our application.
In the code you provided, the port number is custom and can be set as desired. Generally, we can choose some unoccupied port numbers, such as 8888.
2) Correspondingly, does the port number of the client also need to be set to the same value?

If the port number of the server is set to 8888, the client also needs to specify the port number as 8888 when connecting to the server. In this way, the client can connect to the correct port and communicate with the server. In Socket communication, the port number is used to identify the server program or the client program, so when communicating between the client and the server, the port number must be consistent to successfully establish a connection.

Supplementary network planning knowledge

Part of the answer comes from chatgpt
1) Special address: 127.0.0.1

127.0.0.1 is a special IP address, also known as the local loopback address . It points to the network interface of the machine, that is to say, when you access this address, you are actually accessing the machine itself. This address is usually used to test network applications, and when installing some server software on this machine, you can use this address for testing. For example, when you have installed a web server on this machine, you can use a browser to visit 127.0.0.1 to test whether the web server works normally.
2)
Host = socket.gethostbyname(socket.gethostname()) and host="127.0.0.1" mean the same thing?
host = socket.gethostbyname(socket.gethostname()) and host="127.0.0.1" are not exactly the same, although they can both be used to specify the IP address of the machine.
socket.gethostbyname(socket.gethostname()) will return the IP address of the current host, which can be a local area network IP address or a public network IP address. If your computer is connected to a LAN, then this IP address can be used to communicate within the LAN.
host="127.0.0.1" means to use the local loopback address (loopback address), which is 127.0.0.1. This address is a special IP address, which can only be used inside the machine, and cannot be used for communication in the local area network or the public network.
In the above code, use socket.gethostbyname(socket.gethostname()) to get the IP address of the machine, so that you can communicate in the LAN. If you just communicate within the machine, you can also use host="127.0.0.1".

3) The difference between inter-process communication and socket communication
Inter-process communication and socket communication are two different communication methods, and their implementation mechanisms and application scenarios are different.
Inter-Process Communication (IPC, Inter-Process Communication) refers to the communication mechanism between different processes running on the same computer, and is mainly used to realize data transmission between different applications on the same computer. The IPC mechanism can be implemented through named pipes, shared memory, message queues, semaphores, etc., all of which are implemented through APIs provided by the operating system. The advantage of IPC communication is fast speed and high reliability, but it can only communicate on the same computer.
Socket communication is a network-based communication method, which is realized through a set of standard TCP/IP protocols, and can realize data transmission between different computers. Socket communication is a connection-oriented communication method. During the communication process, steps such as connection establishment, data transmission, and connection disconnection are required, so its implementation is more complicated than IPC. The advantage of Socket communication is that it can communicate between different computers and realize cross-network data transmission, but compared with IPC, the speed of Socket communication will be slightly slower.
In short, both inter-process communication and Socket communication have their own advantages and disadvantages, and the appropriate communication method needs to be selected according to the specific application scenario. If you only need to communicate on the same computer, you can choose the IPC mechanism; if you need to communicate between different computers, you can choose Socket communication.

4) Are socket communication and network communication a concept?

Socket communication and network communication are related concepts, but they are not completely equivalent.
Network communication refers to the process of data transmission through a computer network, including a variety of different communication methods and protocols, such as TCP/IP, HTTP, FTP, etc. The purpose of network communication is to transfer data from one computer to another so that different computers can transfer information to each other.
Socket communication is a network-based communication method, which is realized through a set of standard TCP/IP protocols. In Socket communication, data transmission needs to be processed by the network protocol stack, among which the TCP/IP protocol is one of the most commonly used network protocols. Socket communication is a connection-oriented communication method. During the communication process, steps such as connection establishment, data transmission, and connection disconnection are required, so its implementation is more complicated than other network communication methods.
Therefore, it can be said that Socket communication is a specific implementation of network communication, which is realized through the TCP/IP protocol . Network communication covers a variety of different communication methods and protocols, and Socket communication is one of the implementation methods.

5) What is the string encoding and byte sequence?
When we need to transmit data over the network, we need to encode the data into a sequence of bytes before it can be transmitted over the network. In Python, strings are stored in Unicode, so strings need to be encoded as byte sequences to be transmitted over the network.
Here's an example, encoding a string as a sequence of bytes:

s = “hello world”
b = s.encode()

print(b) # b’hello world’

In this example, we first define a string s, then use the s.encode() method to encode it into a byte sequence b, and print it out. The output is b'hello world', indicating that the string "hello world" has been encoded as a bytes type object.
When the receiver receives the sequence of bytes, it needs to be decoded into a string for processing. Here is an example of decoding a sequence of bytes to a string:

b = b’hello world’
s = b.decode()

print(s) # hello world

In this example, we first define a byte sequence b, then use the b.decode() method to decode it into a string s, and print it out. The output is hello world, indicating that the byte sequence b'hello world' has been decoded into the string "hello world".

Guess you like

Origin blog.csdn.net/weixin_46274756/article/details/130146222