socket编程实现聊天室
时间: 2023-12-19 18:31:01 浏览: 78
以下是使用Python socket模块实现简单聊天室的代码示例:
服务端代码:
```python
import socket
import threading
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 绑定端口号
server_socket.bind((host, port))
# 设置最大连接数,超过后排队
server_socket.listen(5)
# 客户端列表
clients = []
# 广播消息
def broadcast(msg):
for client in clients:
client.send(msg)
# 处理客户端消息
def handle_client(client_socket, addr):
while True:
try:
msg = client_socket.recv(1024)
if msg:
print(f"{addr}:{msg.decode('utf-8')}")
broadcast(msg)
else:
remove(client_socket)
except:
continue
# 移除客户端
def remove(client_socket):
if client_socket in clients:
clients.remove(client_socket)
# 监听客户端连接
while True:
client_socket, addr = server_socket.accept()
clients.append(client_socket)
print(f"{addr} 连接到服务器")
client_socket.send("欢迎进入聊天室!".encode('utf-8'))
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr))
client_thread.start()
```
客户端代码:
```python
import socket
import threading
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 连接服务端
client_socket.connect((host, port))
# 接收服务端消息
def receive():
while True:
try:
msg = client_socket.recv(1024)
print(msg.decode('utf-8'))
except:
print("连接已断开")
client_socket.close()
break
# 发送消息
def send():
while True:
msg = input()
client_socket.send(msg.encode('utf-8'))
# 启动接收消息线程
receive_thread = threading.Thread(target=receive)
receive_thread.start()
# 启动发送消息线程
send_thread = threading.Thread(target=send)
send_thread.start()
```
使用方法:
1. 运行服务端代码,等待客户端连接。
2. 运行客户端代码,输入用户名。
3. 客户端连接成功后,可以在控制台输入消息进行聊天。
阅读全文