Python socket programming (1), pythonsocket
Socket is often called a Socket and has become a network programming standard that Windows, mac, and other operating systems comply. It can be used to implement communication between different computers through the network or between different processes on the same host. To use socket for network development, you need to understand the socket primitive of the server and client. There are the following primitives:
Socket (): Create a socket object. parameters include the transport layer protocol type and network layer address type.
Bind (): bind. Enter the IP address and port to bind in the parameter.
Listen (): listener. Used on the server to notify the system to listen to the IP address and port bound to bind and to listen to connections from the client. You can specify the maximum number of connections that can be queued.
Connect (): connection. When using the client, you must specify the server address and port number in the parameters.
Accept (): receives connections. When used on the server side, extract one from the listening connection queue and package it into a new socket object to communicate with the client requesting the request.
Send (): send data. Both ends are available. The parameter is the data to be sent. python3 supports bytes data.
Recv (): receives data. Both ends can be used. You can specify the size of the received data in the parameter.
Close (): close the connection.
The following is a specific example: the client sends a string, and the server converts it into a large write and returns it to the client.
Server:
# Import socket module
Import socket
# Create a socket object
Server = socket. socket ()
# Binding addresses and ports
Server. bind ('localhost', 6969 ))
# Listening for connections
Server. listen (5)
Print ("waiting for connection .....")
# Accepting connections cyclically
While True:
# Accepting connections and returning connected objects
Conn, addr = server. accept ()
Print ("connection successful ......")
Print (conn, addr)
# Circular receipt
While True:
Data = conn. recv (1024)
# Decodes accepted data into the str type for output
Print ("recv:", data. decode ())
# Convert data into uppercase and send it to the client
Conn. send (data. upper ())
# Closing a connection
Server. close ()
Client:
Import socket
Client = socket. socket ()
# Connecting to the server
Client. connect ("localhost", 6969 ))
# Send data cyclically
While True:
# User input string
Msg = input (">>:"). strip ()
# Sending data
Client. send (msg. encode ())
# Accept data sent from the client
Data = client. recv (1024)
# Print data
Print ("recv:", data. decode ())
# Closing a connection
client.close()