在看视频自学 python 时,学习到 socket 模块,简单的服务端与客户端之间的通讯。代码很简单,但是这是刚刚开始。
#Server import socket host = '127.0.0.1' port = 8989 server = socket.socket() server.bind((host,port)) server.listen(5) while True: conn,addr = server.accept() print(conn,addr) while True: data = conn.recv(1024) if not data:break conn.sendall(b'%s recv ok !'%data) print(data.decode('utf-8')) conn.close() server.close() #Client import socket host = '127.0.0.1' port = 8989 client = socket.socket() client.connect((host,port)) while True: send_data = input('>>:') if len(send_data) == 0:continue client.sendall(send_data.encode('utf-8')) data = client.recv(1024).decode('utf-8') print(data) client.close()