编写一个udp通信程序,包含服务器和客户端代码,服务器端实现多线程编程。
时间: 2024-03-20 13:44:04 浏览: 70
多线程UDP通讯程序
3星 · 编辑精心推荐
好的,以下是一个简单的UDP通信程序,包含服务器和客户端代码,服务器端实现了多线程编程。
服务器端代码:
```python
import socket
import threading
HOST = '127.0.0.1'
PORT = 8888
def handle_client(client_socket, addr):
while True:
data, addr = client_socket.recvfrom(1024)
print('Received from {}: {}'.format(addr, data.decode()))
client_socket.sendto(data, addr)
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((HOST, PORT))
print('Server started on {}:{}'.format(HOST, PORT))
while True:
client_socket, addr = server_socket.accept()
print('Client connected from {}:{}'.format(addr[0], addr[1]))
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr))
client_thread.start()
if __name__ == '__main__':
main()
```
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
def main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
message = input('Enter message to send: ')
client_socket.sendto(message.encode(), (HOST, PORT))
data, addr = client_socket.recvfrom(1024)
print('Received from {}: {}'.format(addr, data.decode()))
if __name__ == '__main__':
main()
```
在运行程序前,需要在终端中启动服务器端程序:
```
$ python server.py
```
然后在另一个终端中启动客户端程序:
```
$ python client.py
```
接着,客户端会要求您输入要发送的消息,您可以输入任何内容并按回车键发送。服务器将收到该消息并发送一个确认消息。客户端将收到确认消息并输出它们。
阅读全文