socket programming steps
- The server creates a socket, binds the address and port, and then listens for incoming connections on the port. Once a connection comes in, it receives the incoming connection through the accept function.
- The client also creates a socket. Bind the remote address and port, then establish a connection and send data.
family Address family, used with the first parameter of the socket() function. There are mainly the following
- socket.AF_UNIX is used to communicate with processes under a single machine
- socket.AF_INET is used to communicate with the server, usually this is used.
- socket.AF_INET6 支持 IPv6
sockettype socket type, used with the second parameter of the socket() function, commonly used are
- socket.SOCK_STREAM default, used for TCP protocol
- socket.SOCK_DGRAM for UDP protocol
Server
import socket server = socket.socket() server.bind(('127.0.0.1', 6969)) server.listen() #Start listening # conn is a connection instance generated by the client when the client connects and the server generates it conn, addr = server.accept() #Wait for the session link # print(conn,addr) # You can print the contents of conn and addr #Received data data = conn.recv(1024 ) #Print received data print ( ' recv: ' , data) #Return data conn.send(data.upper())
client
import socket #Declare the socket type and generate a socket connection object at the same time client = socket.socket() #Start connecting client.connect (( ' 127.0.0.1 ' , 6969 )) #Send message Note 3. The above version can only send binary data client .send(b ' test socket ' ) #Receive data data = client.recv(1024 ) #Print receive data print ( ' recv: ' , data) #Close the connection client.close()