学习网络编程的第一天,看着视频教程跟着做了一天聊天小工具
效果图展示:
客户端:
服务器端:
客户端python代码:
from socket import * # 创建客户端套接字对象 client_socket = socket(AF_INET, SOCK_STREAM) # 调用connect方法与服务器建立连接 client_socket.connect(('192.168.31.175', 8989)) while True: # 客户端发送信息 msg = input('>') client_socket.send(msg.encode('utf-8')) # 客户端接收信息 recv_data = client_socket.recv(1024) print('对方说:', recv_data.decode('utf-8'))
服务器端python代码:
from socket import * # 创建服务器端套接字对象 server_socket = socket(AF_INET, SOCK_STREAM) # 绑定端口 server_socket.bind(('', 8989)) # 监听 server_socket.listen() # 等待客户端连接 client_socket, client_info = server_socket.accept() while True: # 接受客户端信息 recv_data = client_socket.recv(1024) print('对方说:', recv_data.decode('utf-8')) # 发送信息 msg = input() client_socket.send(msg.encode('utf-8'))
评论 (0)