服务器
import socket # 待bind的ip/port ip_port = ('127.0.0.1', 9999) # 建立socket s = socket.socket() # 绑定ip/port s.bind(ip_port) # 监听连接 s.listen() print('等待用户连接中... ...') while (True): # 建立连接后,将accept()返回的元组赋值给conn, addr conn, addr = s.accept() if conn is not None: print('有一个用户已连接') b='' while (True): try: if b=='': print('等待对方输入聊天ID') b = conn.recv(1024) a = input("请输入你的聊天ID:") a = a ':' conn.send(bytes(a, encoding='utf-8')) else: recv_data = conn.recv(1024) # 显示接收的信息 print(str(b,encoding='utf-8'), str(recv_data, encoding='utf-8')) send_data = input(a).strip() conn.send(bytes(send_data, encoding='utf-8')) except Exception: print('远程主机强迫关闭了一个现有的连接,续继等待其它的连接。') break
客户端
import socket # 待建立连接HOST的ip/port ip_port = ('127.0.0.1', 9999) # 建立socket s = socket.socket() # 建立连接 s.connect(ip_port)a="" while (True): # 待发送的信息 if a=="": a=input("请输入你的聊天ID:") a=a ':' s.send(bytes(a, encoding='utf-8')) print('等待对方输入聊天ID') b = s.recv(1024) else: send_data = input(a).strip() s.send(bytes(send_data, encoding='utf-8')) recv_data = s.recv(1024) print(str(b,encoding='utf-8'), str(recv_data, encoding='utf-8'))s.close()
暂无评论