This is the 31st day of my participation in the August More Text Challenge

Hello, I’m Brother Chen

Today we will teach you how to program a Socket network using Python

(Make a chat program)

Can be realized in different hosts (computers) between the call.

How is it going to work? Let’s move on

You can see that the client (top) sends the content to the server (bottom), and the server replies

[Note: The client is my local machine, and the server is another host (Ali Cloud server)]

Purpose of two hosts: Verify that two hosts can communicate with each other

socket

Socket (socket for short) is a way of interprocess communication. One of the main differences between it and other interprocess communication is that it can achieve interprocess communication between different hosts.

Most of our various services on the network are based on Socket to complete communication, such as browsing the web, QQ chat, sending and receiving emails and so on

Simply put: Socket can realize communication between different hosts

Socket communication conditions: IP address and port

IP I believe everyone is unfamiliar, every host has an IP, the primary premise of communication between different hosts is that IP can exchange visits, in addition to a condition is the port, such as we often hear 80 port, 3306 port, 8080 port, etc..

Data on the host is sent and received through ports, and the corresponding ports must be enabled for communication.

Image metaphors

An IP is a home address, and a port is a door or window

Example:

(Host A) The Courier needs to know the address of your home (host B’s IP) to deliver the package to you (host B’s port). When he arrives at your door, he needs you to open the door (host B’s port) to get the package.

The client sends (host A) and the server receives (host B). Of course, each host can play two roles (both client and server), so that the two hosts can send and receive each other.

After seeing this, I believe we all know the general meaning of socket between different hosts communication, let’s start Python code implementation.

Client implementation process

First, analyze the implementation process of the client (host A)

from socket import *
# 1. Create a socket
tcp_socket = socket(AF_INET,SOCK_STREAM)
# 2. Prepare the connection server and establish the connection
serve_ip = "Server side (Host B) IP address"
serve_port = 8000  Port 8000
tcp_socket.connect((serve_ip,serve_port))  Connect to the server, set up the connection, parameter is a tuple form

Copy the code

First, establish a connection with the server receiver (host B). The connection condition (IP and port of host B), port 8000 here refers to the port that sends data to host B (host B will listen on port 8000 and then receive data).

Prepare the data to be transmitted
send_data = "Today is August 29, 2021, Brother Chen has sent data to the server."
tcp_socket.send(send_data.encode("gbk")) 
Receive data from the server
# Note the 1024byte value. The size can be set as required
from_server_msg = tcp_socket.recv(1024)
Decode (" GBK ") resolves garbled code
print(from_server_msg.decode("gbk"))  
# close the connection
tcp_socket.close()
Copy the code

Send_data is the content sent to the server (host B), and from_server_msg is the content sent from the server (host B) to the client (host A)

That’s the end of the client code

Server implementation process

Analyze the implementation process of the server side (host B)

from socket import  *
Create a socket
tcp_server = socket(AF_INET,SOCK_STREAM)
# bind IP, port
The default IP address is local
address = (' '.8000)
tcp_server.bind(address)
Start passive connection
# How many clients can connect
tcp_server.listen(128)  
The default attribute for sockets created using sockets is active
Use Listen to make it passive, so you can receive links from others
Copy the code

Server side (host B) IP can be left blank (default host), port 8000 (because the client sends data to port 8000, so the server needs to listen on port 8000, the same as the client port)

Create receive
If a new client connects to the server, a new socket is generated to serve that client
client_socket, clientAddr = tcp_server.accept()
Copy the code
The client_socket is used to serve the client, saving the tcp_server_socket proxy for the tcp_server socket to wait for links from other new clientsReceive the data sent by the other party
from_client_msg = client_socket.recv(1024)Recv is not a tuple, it is not UDP
print("Received data:",from_client_msg.encode("gbk"))
Send data to the client
send_data = client_socket.send("Hello client, received server, public number [Python researcher]".encode("gbk"))
Close the socket
# close the socket serving this client, which means that it can no longer serve this client
# If you still need the service, you can only reconnect it again
client_socket.close()
Copy the code

From_client_msgs indicates that the server (host B) receives data from the client (host A). Send_data indicates that the server (host B) sends data to the client (host A)

That’s the end of the server-side code

Warning: Port 8000 on the server must be enabled; otherwise, communication cannot be carried out

demo

Start (execute) the program on the server (host B) and then execute the program on the client (host A).

You can see that the client (top) sends the content to the server (bottom), and the server replies

Send and response content:

Client send: today is August 29, 2021, Brother Chen sent data to the server

The server receives and replies to the client: Hello client, the server received, public number

Implement continuous communication process

The above GIF demonstrates the one-time communication process between the client and the server. The sending of the client and receiving of the server can be put into a loop to realize continuous communication.

The client

while(1):
    send_data = input("Please enter:")
    #send_data = "Today is August 29, 2021, I sent data to server"
    tcp_socket.send(send_data.encode("gbk"))
    if send_data == "exit":
         break;
    Receive data from the server
    # Note the 1024byte value. The size can be set as required
    from_server_msg = tcp_socket.recv(1024)
    Decode (" GBK ") resolves garbled code
    print(from_server_msg.decode("gbk"))
# close the connection
tcp_socket.close()
Copy the code

The service side


while(1) :Receive the data sent by the other party
    from_client_msg = client_socket.recv(1024)Recv is not a tuple, it is not UDP
    if(from_client_msg=="exit") :break
    print("Received data:",from_client_msg.decode("gbk"))
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    Send data to the client
    send_data = client_socket.send((str(now_time)+"Server: Hello client, server received, public number [Python researcher]").encode("gbk"))
    Close the socket
    # close the socket serving this client, which means that it can no longer serve this client
    # If you still need the service, you can only reconnect it again
client_socket.close()
Copy the code

The client can continuously send data to the server. After receiving the data, the server prints and returns the data to the client

The server returns:

Current system time + server: Hello client, server received, public number

Finally, when the client enters: exit, it disconnects from the server