Socket is a continuation of I/O in the operating system. It can make communication between processes and machines possible. Socket can be regarded as a standard file descriptor. The difference is that the file needs to be opened using the open () function, while the socket uses socket ()
Function creation. recv (), send (), and read (), write () functions are very similar.
TCP generally uses accept () to create a new scoket for each connected client. Generally, UDP only uses a single socket and relies entirely on the value returned by recvfrom () to determine where to send a response.
Client:
1. Create a socket:
// AF_INET indicates IPv4
= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2. Connect to the socket
The socket connection requires a tuple parameter to provide the IP address and port number:
s.connect((“www.example.com”, 80))
3,
= = socket.getservbyname(, % , s.getpeername()
File objects:
= 70= sys.argv[1= sys.argv[2== s.makefile(+ line
Advanced Interface:
= urllib.urlopen(sys.argv[1 1= f.read(2048
Server:
1. Create a connection:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2. Set socket options:
//1)
3. Bind a socket:
s.bind((host, port))
4. Listener:
s.listen(1)
5. Accept connections:
1=
6,
= Port = 51423 = 1 # It is set that there is only one request waiting for processing at a time. The real server will set a high number. S. listen (1 1 =
Use UDP:
= port = 51423=1 1= s.recvfrom(8192