import socket
import threading
import time
MSG_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 = True
while connected:
try:
msg_len = client_socket.recv(MSG_LENGTH).decode('utf-8') #接收消息长度
except ConnectionResetError:
global connections
connections -= 1
print(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 = False
print(f'客户机:{client_addr}断开了连接!')
connections -= 1
print(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 += 1
print(f'服务器当前活动连接数量是:{connections}')
import socket
MSG_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':
break
send_recv(inputStr) # 发送消息和接收消息
send_recv(DISCONNECTED)
client_socket.close()
启动服务端:
启动客户端1并发送消息:
启动客户端2并发送消息:
启动客户端3并发送消息:
关闭客户机2: