服务端代码:
#!/usr/bin/env python3 from socket import * from time import ctime HOST='服务器地址' PORT=33333 BUFSIZ=1024 ADDR=(HOST,PORT) tcpS=socket(AF_INET,SOCK_STREAM) tcpS.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) tcpS.bind(ADDR) tcpS.listen(5) while True: print("wating for connection...") tcpC,addr=tcpS.accept() print("...connected from",addr) while True: data=tcpC.recv(BUFSIZ) if not data: break data=data.decode('utf-8') respMSG="[%s]%s"%(ctime(),'utf-8') tcpC.send(bytes(respMSG,'utf-8')) tcpC.close() tcpS.close()
客户端代码:
#!/usr/bin/env python3 from socket import * HOST='服务器地址' PORT=33333 BUFSIZ=1024 ADDR=(HOST,PORT) tcpC=socket(AF_INET,SOCK_STREAM) tcpC.connect(ADDR) while True: data=input(">>>") if not data: break tcpC.send(bytes(data,'utf-8')) data=tcpC.recv(BUFSIZ) if not data: break print(data.decode('utf-8')) tcpC.close()
服务端运行
客户端运行: