server.py
import socket ip_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) # 欢迎登陆 =》xe6xacxa2xe8xbfx8exe7x99xbbxe9x99x86 # 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 socket ip_port = ('127.0.0.1', 9999) sk = socket.socket() sk.connect(ip_port) while True: # recv返回值=字节类型 server_reply_bytes = sk.recv(1024) #xe6xacxa2xe8xbfx8exe7x99xbbxe9x99x86 # 字符串 = 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()