linux网络聊天室的设计与实现客户端 服务端代码
时间: 2023-08-13 07:07:30 浏览: 108
以下是一个简单的Linux网络聊天室的客户端和服务端代码示例:
服务端代码:
```python
import socket
import threading
# 创建TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 监听客户端连接
server_socket.listen(5)
print('Server is listening...')
# 存储所有已连接的客户端套接字
client_sockets = []
# 处理客户端请求的函数
def handle_client(client_socket, client_address):
print('New connection from', client_address)
# 将客户端套接字存储到列表中
client_sockets.append(client_socket)
while True:
try:
# 接收客户端发送的消息
message = client_socket.recv(1024).decode()
if message:
print('Received message:', message)
# 将消息发送给所有已连接的客户端
for socket in client_sockets:
if socket != client_socket:
socket.sendall(message.encode())
else:
print('Connection from', client_address, 'closed')
client_sockets.remove(client_socket)
client_socket.close()
break
except:
print('Connection from', client_address, 'closed')
client_sockets.remove(client_socket)
client_socket.close()
break
# 处理客户端连接的函数
def accept_clients():
while True:
client_socket, client_address = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
# 启动处理客户端连接的线程
client_thread = threading.Thread(target=accept_clients)
client_thread.start()
```
客户端代码:
```python
import socket
import threading
# 创建TCP/IP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 发送消息的函数
def send_message():
while True:
message = input('Enter message: ')
client_socket.sendall(message.encode())
# 接收消息的函数
def receive_message():
while True:
message = client_socket.recv(1024).decode()
print('Received message:', message)
# 启动发送消息和接收消息的线程
send_thread = threading.Thread(target=send_message)
recv_thread = threading.Thread(target=receive_message)
send_thread.start()
recv_thread.start()
```
以上仅是一个简单的示例,实际的Linux网络聊天室需要考虑更多的功能和安全性问题。
阅读全文