Python socket programming (write server instance) + difference and use of send and sendall, programming introduction sendall
To compile a server in python, follow these steps:
1. The first step is to create a socket object. Call the socket constructor. For example:
Socket = socket. socket (family, type)
The family parameter represents the address family, which can be AF_INET or AF_UNIX. The AF_INET family includes Internet addresses, and the AF_UNIX family is used for communication between processes on the same machine.
The type parameter represents the socket type, which can be SOCK_STREAM (stream socket) and SOCK_DGRAM (datagram socket ).
2. The second step is to bind the socket to the specified address. This is implemented through the bind method of the socket object:
Socket. bind (address)
The address of a socket created by AF_INET must be a dual-element tuple in the format of host and port ). Host indicates the host, and port indicates the port number. If the port is in use, the host name is incorrect, or the port is retained, the bind method will cause a socket. error exception.
3. Step 3 is to use the listen method of socket to receive connection requests.
Socket. listen (backlog)
Backlog specifies the maximum number of customers allowed to connect to the server. The value must be at least 1. After receiving the connection request, these requests need to be queued. If the queue is full, the request is rejected.
4. Step 4 is to wait for the client to request a connection through the socket accept method.
Connection, address = socket. accept ()
When the accept method is called, the socket enters the "waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is the new socket object, and the server must communicate with the customer through it; the second element address is the customer's Internet address.
5. The fifth step is the processing stage. The server and client communicate (transmit data) through the send and recv methods ). The server calls send and uses a string to send messages to the customer. The send method returns the number of sent characters. The server uses the recv method to receive information from the customer. When calling recv, the server must specify an integer, which corresponds to the maximum data volume that can be received through this method call. The recv method enters the "blocked" status when receiving data, and returns a string that indicates the received data. If the amount of data sent exceeds the recv limit, the data will be truncated. The excess data is buffered at the receiving end. When recv is called in the future, excess data will be deleted from the buffer zone (and any other data that the customer may send since the last recv call ).
6. When the transfer is over, the server calls the close method of socket to close the connection.
Follow these steps to write a client in python:
1. Create a socket to connect to the server: socket = socket. socket (family, type)
2. Use the connect Method of socket to connect to the server. For the AF_INET family, the connection format is as follows:
Socket. connect (host, port ))
Host indicates the server host name or IP address, and port indicates the port number bound to the server process. If the connection is successful, the customer can communicate with the server through the socket. If the connection fails, the socket. error exception will occur.
3. In the processing phase, the customer and the server will communicate with the recv method through the send method.
4. After the transmission ends, the customer calls the close method of socket to close the connection.
The following is a simple example:
Server. py
From datetime import datetimeimport socketaddress = ('localhost', 6789) max_size = 1000 print ('start server {}'. format (datetime. now () print ('Waiting for a client now! ') Server = socket. socket (socket. AF_INET, socket. SOCK_STREAM) ''' socket. AF_INET indicates creating an IP socket; socket. SOCK_STREAM indicates a streaming socket, and for TCPsock_DGRAM indicates a datagram socket, for UDP ''' server. bind (address) ''' the server must use two methods in the socket package to establish a network connection. The first method is socket. socket, it will create an empty socket; the second is bind will bind (listen to all data of this IP address and port) to this socket '''server. listen (5) ''' indicates that a maximum of five clients can be connected. If more than five clients are connected, ''' client, addr = server, is rejected. when the accept () ''' method is called, the socket enters the "waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is a new socket object, and the server must communicate with the customer through it. The second element address is the customer's Internet address '''data = client. recv (max_size) ''' specifies the maximum length of a message that can be accepted is 1000 bytes ''' print ("AT", datetime. now (), client, "Said", data) client. sendall (B 'Are you want to talk to Me') client. close () server. close ()
Client. py
import socketfrom datetime import datetimeaddress = ('localhost',6789)max_size =1000print("Start the client at {}".format(datetime.now()))client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)client.connect(address)client.sendall(b'Hey~~~')data = client.recv(max_size)print("AT",datetime.now(),"some reply" , data)client.close()
Run server. py on the terminal, and then run clien. py
Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------------
Difference and usage of send and sendall in python socket Functions
In python socket programming, there are two TCP sending functions: send () and sendall (). The differences are as follows:
Socket. send (string [, flags])Send TCP data and return the size of the sent bytes. The length of this Byte may be less than the length of the data to be sent. In other words, if this function is executed once, the given data may not be sent completely. It may need to be repeated multiple times before the function can be sent completely.
Example:
data = "something you want to send" while True: len = s.send(data[len:]) if not len: break
Socket. sendall (string [, flags])After reading the above, this function is easy to understand. Send the complete TCP data. If the TCP data is successfully sent, None is returned. If the TCP Data fails, an exception is thrown.
Example:
data = "something you want to send" s.sendall(data)