使用tcp socket 实现聊天室私聊功能,服务器和客户端代码
时间: 2024-02-21 08:58:51 浏览: 154
好的,下面是一个简单的聊天室私聊功能的示例代码,使用 TCP Socket 实现,包括服务器和客户端代码。请注意,这只是一个示例,实际应用中可能需要更多的错误处理和安全性检查。
服务器代码:
```python
import socket
# 创建 TCP Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 监听连接
server_socket.listen(5)
# 存储已连接的客户端 Socket 和昵称
clients = {}
nicknames = {}
print('Server started, waiting for connections...')
while True:
# 接受连接
client_socket, client_address = server_socket.accept()
# 接收客户端昵称
nickname = client_socket.recv(1024).decode()
# 存储客户端 Socket 和昵称
clients[client_socket] = client_address
nicknames[client_socket] = nickname
print(f'New connection from {client_address[0]}:{client_address[1]}, nickname: {nickname}')
# 广播新用户加入消息
for sock in clients:
message = f'{nickname} has joined the chat!'
sock.send(message.encode())
while True:
# 接收消息
data = client_socket.recv(1024).decode()
if not data:
break
# 解析消息
parts = data.split(' ', 1)
if len(parts) != 2:
message = 'Invalid command, usage: /msg <nickname> <message>'
client_socket.send(message.encode())
continue
recipient_nickname, message = parts
# 查找收件人 Socket
recipient_socket = None
for sock, nickname in nicknames.items():
if nickname == recipient_nickname:
recipient_socket = sock
break
if not recipient_socket:
message = f'User {recipient_nickname} not found'
client_socket.send(message.encode())
continue
# 发送私聊消息
message = f'{nickname} (private): {message}'
recipient_socket.send(message.encode())
# 关闭客户端连接
message = f'{nickname} has left the chat.'
print(message)
del clients[client_socket]
del nicknames[client_socket]
client_socket.close()
# 广播用户离开消息
for sock in clients:
sock.send(message.encode())
```
客户端代码:
```python
import socket
import threading
# 创建 TCP Socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 输入昵称
nickname = input('Enter your nickname: ')
client_socket.send(nickname.encode())
# 接收消息并输出
def receive():
while True:
message = client_socket.recv(1024).decode()
print(message)
# 输入并发送消息
def send():
while True:
message = input()
# 判断是否为私聊命令
if message.startswith('/msg'):
parts = message.split(' ', 2)
if len(parts) != 3:
print('Invalid command, usage: /msg <nickname> <message>')
continue
recipient_nickname, message = parts[1:]
message = f'/msg {recipient_nickname} {message}'
client_socket.send(message.encode())
# 启动接收和发送线程
receive_thread = threading.Thread(target=receive)
receive_thread.start()
send_thread = threading.Thread(target=send)
send_thread.start()
```
在客户端输入 `/msg <nickname> <message>` 命令可以向指定昵称的用户发送私聊消息。例如,输入 `/msg Alice Hello Alice!` 可以向昵称为 `Alice` 的用户发送私聊消息。
需要注意的是,该示例代码没有加入任何的安全性检查和错误处理,实际应用中需要加入相关处理以提高系统的可靠性和安全性。
阅读全文