基于UDP的简易聊天室代码
时间: 2023-09-08 21:11:55 浏览: 47
下面是基于UDP的简易聊天室的Python代码示例:
服务器端代码:
```python
import socket
import threading
# 客户端信息列表
clients = []
# 创建UDP Socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口号
host = '127.0.0.1'
port = 8888
server_socket.bind((host, port))
# 接收数据的函数
def receive_data():
while True:
# 接收数据报
data, addr = server_socket.recvfrom(1024)
message = data.decode('utf-8')
print(f'{addr[0]}:{addr[1]}说:{message}')
# 转发数据给所有客户端
for client in clients:
if addr != client:
server_socket.sendto(data, client)
# 发送数据的函数
def send_data():
while True:
# 从标准输入获取数据
message = input()
# 将数据发送给所有客户端
for client in clients:
server_socket.sendto(message.encode('utf-8'), client)
if __name__ == '__main__':
# 启动接收数据的线程
receive_thread = threading.Thread(target=receive_data)
receive_thread.start()
while True:
# 接收客户端连接
data, addr = server_socket.recvfrom(1024)
if addr not in clients:
clients.append(addr)
print(f'{addr[0]}:{addr[1]}已连接')
# 启动发送数据的线程
send_thread = threading.Thread(target=send_data)
send_thread.start()
```
客户端代码:
```python
import socket
import threading
# 创建UDP Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 服务器IP地址和端口号
server_host = '127.0.0.1'
server_port = 8888
# 发送数据的函数
def send_data():
while True:
# 从标准输入获取数据
message = input()
# 将数据发送到服务器
client_socket.sendto(message.encode('utf-8'), (server_host, server_port))
# 接收数据的函数
def receive_data():
while True:
# 接收数据报
data, addr = client_socket.recvfrom(1024)
message = data.decode('utf-8')
print(f'{addr[0]}:{addr[1]}说:{message}')
if __name__ == '__main__':
# 启动发送数据的线程
send_thread = threading.Thread(target=send_data)
send_thread.start()
# 启动接收数据的线程
receive_thread = threading.Thread(target=receive_data)
receive_thread.start()
```
以上是基于UDP的简易聊天室的Python代码示例,您可以根据需求进行相应的修改和完善。需要注意的是,这只是一个简单的示例,实际应用中还需要考虑一些其他的因素,比如数据的安全性、数据的可靠性等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)