Socket implementation in Python server and client 3-1

The network server and client communicate through sockets. The steps for creating a server and client via sockets are different.

1 Steps to create a server

The steps to create the server are shown in Figure 1.

Figure 1 Create server

First create and bind the socket; then listen on the created socket to see if a client connects to the server through the socket. If there is no connection, it will keep listening. If there is a connection, it will receive data from the client. Connect, obtain the client's data and create a new socket for subsequent data communication with the client; then determine whether the client has data sent on the newly created socket, if not, keep waiting. , if there is data, receive the data and display it; finally close the two sockets created.

2 Server-side implementation

Follow the steps shown in Figure 1 to implement the server through code.

2.1 Create socket

Before creating a socket, you need to import the socket module, that is, the socket module.

The socket is created through the socket() method in the socket module. The format of this method is

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

Among them, the first parameter family represents the address family of the socket, which is the protocol used by the socket. AF_INET represents that the socket used contains two attributes: IP address and port; the second parameter type represents the socket. Type, SOCK_STREAM represents a stream socket, which is a TCP-based socket; the third parameter proto represents the protocol number, generally set to 0; the fourth parameter fileno is set to None to indicate that the socket will not be automatically detected. parameter.

The code to create a socket using the socket() method is as follows.

s = socket.socket()

As can be seen from the above code, when creating a socket, the default values ​​of the parameters are used, that is, an AF_INET TCP socket is created.

2.2 Bind socket

Bind the socket through the bind() method, which binds the IP address and port number required by the AF_INET protocol to the created socket. The format of this method is as follows.

socket.bind(address)

Among them, address is generally a tuple containing the IP address and port number.

The code to bind a socket using the bind() method is as follows.

HOST = ''
PORT = 12345
s.bind((HOST, PORT))

Among them, s is the socket created in "2.1 Creating Sockets". Because the server binds the socket itself, there is no need to specify the server's IP address HOST, only the listening port value PORT.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/133749538