import socket sk = socket.socket() address = ('127.0.0.1',8000) sk.bind(address) sk.listen(3)#等待数 print('waiting ..............') # conn = sk.accept() # print(conn) #conn客户端 #不能发空,发空的话就直接阻塞 # conn,addr = sk.accept() # while True: # data = conn.recv(1024) # print('.............', str(data, 'utf8')) # if not data: # conn, addr = sk.accept() # print(addr) # continue #或者 while 1: conn,addr = sk.accept() print(addr) while 1: data = conn.recv(1024) print('..........',str(data,'utf8')) if not data:break inp = input('>>>>') conn.send(bytes(inp,'utf8')) # inp = input('>>>>') # conn.send(bytes(inp,'utf8')) conn.close() sk.close()
这是server端代码
import socket sk = socket.socket() print(sk) address = ('127.0.0.1',8000) sk.connect(address) while True: inp = input('>>>>>') if inp == 'exit': break sk.send(bytes(inp,'utf8')) data = sk.recv(1024) print(str(data,'utf8')) sk.close() print(sk)
这是Client端代码
首先运行server端
然后开启Client端
然后再Client端发送hello,服务器端就会接收到hello
本代码可以在客户端(Client)断开后重连继续发送,类似于和一个人聊天结束之后,可以换下一个人继续聊天