帮我用socket写一款聊天软件
时间: 2023-05-31 21:03:12 浏览: 93
作为AI语言模型,我可以为您提供一个Python的socket聊天程序的基本框架,并向您提供一些参考代码。
客户端代码:
```
import socket
import threading
# 定义服务器地址和端口
SERVER_HOST = 'localhost'
SERVER_PORT = 8000
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect((SERVER_HOST, SERVER_PORT))
# 定义发送消息的函数
def send_message():
while True:
message = input()
client_socket.send(message.encode())
# 定义接收消息的函数
def receive_message():
while True:
message = client_socket.recv(1024).decode()
print(message)
# 创建两个线程,分别用于发送和接收消息
send_thread = threading.Thread(target=send_message)
receive_thread = threading.Thread(target=receive_message)
# 启动线程
send_thread.start()
receive_thread.start()
```
服务器端代码:
```
import socket
import threading
# 定义服务器地址和端口
SERVER_HOST = 'localhost'
SERVER_PORT = 8000
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口
server_socket.bind((SERVER_HOST, SERVER_PORT))
# 监听连接
server_socket.listen()
# 定义一个字典,用于存储客户端和对应的用户名
clients = {}
# 定义发送消息的函数
def send_message(message, sender_socket):
for client_socket in clients:
if client_socket != sender_socket:
client_socket.send(message.encode())
# 定义处理客户端请求的函数
def handle_client(client_socket, client_address):
# 让客户端输入用户名
client_socket.send('Enter your username: '.encode())
username = client_socket.recv(1024).decode()
# 将客户端添加到字典中
clients[client_socket] = username
# 给所有客户端发送欢迎消息
message = '{} has joined the chat'.format(username)
send_message(message, client_socket)
while True:
# 接收客户端发送的消息
try:
message = client_socket.recv(1024).decode()
except:
# 如果客户端断开连接,将其从字典中移除,并给其他客户端发送离开消息
del clients[client_socket]
message = '{} has left the chat'.format(username)
send_message(message, client_socket)
break
# 发送消息给其他客户端
message = '{}: {}'.format(username, message)
send_message(message, client_socket)
# 接受客户端连接请求,并启动线程处理请求
while True:
client_socket, client_address = server_socket.accept()
print('Accepted connection from {}:{}'.format(client_address[0], client_address[1]))
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
```
这只是一个简单的聊天程序,可能还有很多需要完善的地方。希望对您有所帮助。
阅读全文