Python socket module Learning
Python socket module learning: 1. socket: socket. A socket is basically an "information channel" between two endpoints. It is used to describe IP addresses and ports and is a handle to an information chain, an application sends a request to or responds to a network request through a socket. There are two sockets: server socket and client socket. After creating a server socket, wait for the connection. In this way, it listens to a network address (a combination of an IP address and a port number) and knows that there is a client socket connection. After the connection is complete, the two can interact. 2. Three parameters of python socket class instantiation: a and address family (socket by default. AF_INET) B. Stream (socket by default. SOCK_STREAM) or datagram (socket by default. SOCK_DGRAM) c. The protocol used (the default value is 0. Use the default value). 3. Run or use the socket: SERVER: a. Create a socket, bind the socket to the local IP address and port # socket. socket (socket. AF_INET, socket. SOCK_STREAM, 0) # s. the bind () method binds a socket to an address. In AF_INET, the address is expressed in the form of a tuples (host, port. B. Start listening for connection # s. listen () listen (backlog) method: start to listen to TCP incoming connections. backlog specifies the maximum number of connections that the operating system can suspend before the connection is denied. This value must be at least 1, and most applications can be set to 5. C. Initiate a loop and continuously accept client connection requests. # S. accept () accepts TCP connections and returns (conn, address). conn is a new socket object and can be used to receive and send data. Address is the address used to connect to the client. D. Then accept the incoming data and send it to the Peer Data # s. recv () s. sendall () e. After transmission is complete, disable socket # s. close () Client: a. Create a socket and connect to the remote address # socket. socket (socket. AF_INET, socket. SOCK_STREAM, 0) # s. connect () method: connect to the socket at the address. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned. B. send and receive data after connection # s. recv () s. sendall () c. After transmission, close socket # s. close () server. py:
import socketip_port = ('127.0.0.1',9999)sk=socket.socket()sk.bind(ip_port)sk.listen(5)conn,address = sk.accept()conn.send('hello word ')conn.close()client.py:
import socketclient = socket.socket()ip_port = ('127.0.0.1',9999)client.connect(ip_port)data = client.recv(1024)print data