目录
- socket
- 服务端代码
- 客户端代码
- 执行结果
socket
socket基础知识
服务端代码
import socket
import threading
import timeMSG_LENGTH = 64
DISCONNECTED = '!CONNECTION CLOSED'
connections = 0#定义服务器地址
server_ip = socket.gethostbyname(socket.gethostname())
server_port = 5555
server_addr = (server_ip, server_port)#创建服务器套接字并绑定到工作地址
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_addr)def handle_client(client_socket, client_addr):print(f'新连接建立,远程客户机地址是:{client_addr}'+'\n')connected = Truewhile connected:try:msg_len = client_socket.recv(MSG_LENGTH).decode('utf-8') #接收消息长度except ConnectionResetError:global connectionsconnections -= 1print(f'远程客户机{client_addr}关闭了连接,活动连接数量是:{connections}')break;msg_len = int(msg_len)if msg_len > 0:msg = client_socket.recv(msg_len).decode('utf-8') # 接收消息内容if msg == DISCONNECTED: # 收到客户机断开连接的消息connected = Falseprint(f'客户机:{client_addr}断开了连接!')connections -= 1print(f'服务器当前活动连接数量是:{connections}')print(f'来自客户机{client_addr}的消息是:{msg}')# 回送消息echo_message = f'服务器{client_socket.getsockname()}收到消息:{msg},时间:{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}'client_socket.send(echo_message.encode('utf-8'))client_socket.close() # 关闭会话连接server_socket.listen()
print(f'服务器开始在{server_addr}侦听...')while True:new_socket, new_addr = server_socket.accept()client_thread = threading.Thread(target=handle_client, args=(new_socket, new_addr))client_thread.start()connections += 1print(f'服务器当前活动连接数量是:{connections}')
客户端代码
import socketMSG_LENGTH = 64
DISCONNECTED = '!CONNECTION CLOSED'remote_ip = socket.gethostbyname(socket.gethostname())
remote_port = 5555
remote_addr = (remote_ip, remote_port)client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(remote_addr)
print(f'客户机工作地址:{client_socket.getsockname()}')def send_recv(msg):message = msg.encode('utf-8') # 消息编码 发消息需编码msg_len = len(message) # 消息长度str_len = str(msg_len).encode('utf-8') # 长度编码str_len += b' ' * (MSG_LENGTH - len(str_len)) # 空白处补空格client_socket.send(str_len) # 发送消息长度client_socket.send(message) # 发送消息内容echo_message = client_socket.recv(1024).decode('utf-8') # 接收服务器消息print(echo_message)while True:inputStr = input('请输入待发送的字符串(Q:结束会话):')if inputStr.lower() == 'q':breaksend_recv(inputStr) # 发送消息和接收消息send_recv(DISCONNECTED)
client_socket.close()
执行结果
启动服务端:
启动客户端1并发送消息:
启动客户端2并发送消息:
启动客户端3并发送消息:
关闭客户机2: