tcp server
#!/usr/bin/python3 # -*-coding:utf-8 -*- from socket import * import time Of COD = ' UTF-. 8 ' the HOST = ' 0.0.0.0 ' # host IP PORT = 9999 # port number BUFSIZ = 1024 ADDR = (the HOST, PORT) SIZE = 10 TCPS = socket (AF_INET, SOCK_STREAM) # Create a socket object tcpS.setsockopt (SOL_SOCKET, the SO_REUSEADDR,. 1) # were added socket configuration, ip and port reuse tcpS.bind (ADDR) # Binding ip port number tcpS.listen ( SIZE) # set the maximum number of links the while True: Print ( " server starts, listen for client links " ) conn, addr = tcpS.accept () Print ( " Linked clients " , addr) the while True: the try : Data = conn.recv (BUFSIZ) # reads the linked client message sent by the except Exception: Print ( " OFF client " , addr) BREAK Print ( " content sent by the client: " , data.decode (of COD )) IF Not Data: BREAK MSG = The time.strftime ( " %% Y-X-M-% D% " ) # Get structured event timestamp MSG1 = ' [% S]: S% ' % (MSG, data.decode (COD)) conn.send (msg1.encode (COD)) # Send a message to the linked client conn.Close () # close the client link tcpS.close ()
tcp client
#!/usr/bin/python3 # -*-coding:utf-8 -*- from socket import * from time import ctime The HOST = ' 127.0.0.1 ' # server IP PORT = 9999 # service port number BUFSIZ = 1024 ADDR = (the HOST, PORT) tcpCliSock = socket (AF_INET, SOCK_STREAM) # Create a socket object tcpCliSock.connect (ADDR) # connect to the server the while True: Data = INPUT ( ' >> ' ) .strip () IF Not Data: BREAK tcpCliSock.send (data.encode ( ' UTF-. 8 ' )) # Send Message Data = tcpCliSock.recv (BUFSIZ) # read the message IF Not Data: BREAK Print (data.decode ( ' UTF-. 8 ' )) tcpCliSock.close () # close the client
server
Server starts, listen for client links Links client ( ' 127.0.0.1 ' , 56129 ) Content sent by the client: age Content sent by the client: name
client
>>age [2020-03-02 00:24:09]:age >>name [2020-03-02 00:24:13]:name >>