# ### socket server Import socket # create a socket object SK = socket.socket () # ip and port binding (registration network, let others find you) # "127.0.0.1" default of the machine ip sk.bind ( ( "127.0.0.1", 9000)) # turn monitor (wait for others to connect to the server) sk.listen () '' ' # establish a three-way handshake to establish a connection, plus a blocked program, the establishment of three-way handshake If it fails, the program is not down performing '' ' Conn, addr = sk.accept () Print (Conn, addr) # 1024 the maximum received a single byte. blockage added again, no data is received, the code is not executed down msg = conn. the recv (1024) # restored to the byte stream of a normal character string (character string into a byte stream parsing) Print (msg.decode ( "UTF-. 8")) # sent to the client data conn.send ( "I really good yo ".encode (" UTF-8 ")) # waved performed four times, disconnected conn.Close () # close the socket object, return the occupied port number sk.close ()
# ### socket client Import socket # produce a socket object SK = socket.socket () sk.connect (( "127.0.0.1", 9000)) # sends a message (transmitted binary byte stream) sk.send ( "hello what, I'm so yo" .encode ( "UTF-8")) # accept message (after sending, plus program blocks, waiting for the server response data, the largest recipient of 1024 bytes) RES = sk.recv (1024) strvar = res.decode ( "UTF-. 8") Print (strvar) # close the connection sk.close ()