半双工聊天
半双工聊天。创建一个简单的半双工聊天程序。指定半双工,我们的意思就是,当建
立一个连接且服务开始后,只有一个人能打字,而另一个参与者在得到输入消息提示
之前必须等待消息。并且,一旦发送者发送了一条消息,在他能够再次发送消息之前,
必须等待对方回复。其中,一位参与者将在服务器一侧,而另一位在客户端一侧。
# server.py 服务器 from socket import * from time import ctime HOST = '' PORT = 12345 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpServer = socket(AF_INET, SOCK_STREAM) tcpServer.bind(ADDR) tcpServer.listen(5) try: while True: print('waiting for connection...') tcpClient, addr = tcpServer.accept() print('Connected from:', addr) while True: data = tcpClient.recv(BUFSIZ) print('[%s]: %s' % (ctime(), data.decode('utf-8'))) reply = input('> ') tcpClient.send(bytes(reply, 'utf-8')) tcpClient.close() tcpServer.close() except KeyboardInterrupt: print('Bye!')
# client.py 客户端 from socket import * from time import ctime HOST = 'localhost' PORT = 12345 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpClient = socket(AF_INET, SOCK_STREAM) tcpClient.connect(ADDR) try: while True: data = input('> ') tcpClient.send(bytes(data, 'utf-8')) reply = tcpClient.recv(BUFSIZ) print('[%s]: %s' % (ctime(), reply.decode('utf-8'))) except KeyboardInterrupt: print('Bye!')