Python has the widest range of web aspects to apply. Therefore, the socket is very important.
To use the socket, you must introduce a socket module, so write to the beginning of the Python script
1 Import Socket
Learn the socket is known, is the client and the service side of the communication.
So create new client.py and server.py files.
Write the server.py file first:
1 ImportSocket2 3 #creates a socket for the TCP protocol. 4Server =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)5 #the IP address of the connection. 6Host ='127.0.0.1'7 #The destination port. 8Port = 123459Address = ('127.0.0.1', 12345)Ten #listen for the port on the destination address. One Server.bind (address) A #accepts up to 1 connection requests at a time. -Server.listen (1) - the whileTrue: - #Accept the connection. Block the process if there is no connection - #server.accept () returns a tuple. - #clientsocket, clientaddress = server.accept () + #equivalent to - #temp = server.accept () + #clientsocket = temp[0] A #clientaddress = temp[1] atClientsocket,clientaddress =server.accept () - #receive and Decode. 1024 refers to the size of the buffer. - Print(CLIENTSOCKET.RECV (1024). Decode ()) - #the string encoding is concurrently returned to the client. - #equivalent to - #Clientsocket.sendall (b ' reply ') inClientsocket.sendall ('reply'. Encode ()) - #closes the connection to the client. to clientsocket.close () + Else: - #close the socket on the service-side listening port. theServer.close ()
Next write the client.py file:
1 ImportSocket2 3 #creates a socket for the TCP protocol. 4Client =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)5 #Connecting to the destination port, the connection failure throws an exception of type Connectionrefusederror. 6Client.connect (('127.0.0.1', 12345))7 #encodes a string and sends it to the server. 8 #equivalent to9 #client.send (b ' Hello ')TenClient.send ('Hello'. Encode ()) One #receives the contents of the server and decodes the output. A Print(CLIENT.RECV (1024). Decode ()) - #close the socket connected to the server. -Client.close ()
Once you have finished writing, you can run it.
Right-click on the server.py file, then right-click on the client.py file to run it again.
Operating effect:
Python learns socket sockets in -15.python