python写一个聊天窗口_python实现udp聊天窗口
时间: 2023-06-29 17:21:03 浏览: 107
好的,下面是一个简单的 Python 实现 UDP 聊天窗口的代码:
### Server.py
```python
import socket
# 创建一个 UDP socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定到本地主机和一个端口号
server_socket.bind(('localhost', 12345))
while True:
# 接收客户端发送的消息和地址
message, client_address = server_socket.recvfrom(1024)
print(f'Received message "{message.decode()}" from {client_address}')
# 发送消息给客户端
server_socket.sendto(b'Received your message!', client_address)
```
### Client.py
```python
import socket
# 创建一个 UDP socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
# 从用户输入中获取消息并发送给服务器
message = input('Enter message to send: ')
client_socket.sendto(message.encode(), ('localhost', 12345))
# 接收服务器返回的消息
response, server_address = client_socket.recvfrom(1024)
print(f'Received response "{response.decode()}" from {server_address}')
```
在运行这段代码之前,确保你已经安装了 Python。然后分别运行 Server.py 和 Client.py,你就可以开始聊天了!
阅读全文