//服务器端代码 from socket import *from time import ctimehost='localhost'port=3330bufsize = 1024addr = (host,port)tcpser = socket(AF_INET,SOCK_STREAM)tcpser.bind(addr)tcpser.listen(5)while True: print('waiting for connetion....') tcpCliSock,ADDR = tcpser.accept() print('...connection from:',ADDR) while True: data = tcpCliSock.recv(bufsize) if not data: break tcpCliSock.send(('[%s]%s'%(ctime(),data)).encode()) tcpCliSock.close()tcpser.close()
//客户端代码 from socket import *host='localhost'port=3330bufsize = 1024addr = (host,port)tcpser = socket(AF_INET,SOCK_STREAM)tcpser.connect(addr)while True: data = input('>') if not data: break tcpser.send(data.encode()) data = tcpser.recv(bufsize).decode() if not data: break print(data)tcpser.close()
以上代码为python核心编程(第三版)网络编程一节代码,其中一些错误已经被我修改可正常运行