server.py
import socketip_port = ('127.0.0.1',9999)sk = socket.socket()sk.bind(ip_port)sk.listen(5)while True: # 服务端阻塞,等待客户端请求 conn,addr = sk.accept() # 2.7 sendall(str) # 3.5 sendall(bytes) # 欢迎登陆 =》\xe6\xac\xa2\xe8\xbf\x8e\xe7\x99\xbb\xe9\x99\x86 # bytes('欢迎登陆', 'utf-8') conn.sendall(bytes('欢迎登陆', 'utf-8')) while True: client_data = conn.recv(1024) if not client_data: break reply = str(client_data, 'utf-8') conn.sendall(bytes(reply, 'utf-8')) conn.close()
client.py
import socketip_port = ('127.0.0.1', 9999)sk = socket.socket()sk.connect(ip_port)while True: # recv返回值=字节类型 server_reply_bytes = sk.recv(1024) #\xe6\xac\xa2\xe8\xbf\x8e\xe7\x99\xbb\xe9\x99\x86 # 字符串 = str(字节, 'utf-8') reply_str = str(server_reply_bytes, 'utf-8') # reply_str="欢迎登录" print(reply_str) # 字符串->字节 bytes(字符串,'utf-8') # 字节 -> 字符串 str(字节,'utf-8') inp = input("input:") sk.sendall(bytes(inp, 'utf-8'))sk.close()