编写 UDP 程序,通过多路 IO 复用同时处理标准输入和套接字。当输入为 quit 时程序结束;当通过套 接字收到对方消息时回射给对方
时间: 2024-11-25 09:17:39 浏览: 3
基于tcp,编写基于流式套接字的通信程序。
在编写UDP程序时,我们可以利用操作系统提供的多路复用技术,如epoll、kqueue(Linux)、Select或IOCP(Windows),以便在一个事件循环中同时处理标准输入和网络套接字。以下是一个简单的Python示例,使用`selectors`模块实现多路IO复用:
```python
import selectors
import socket
import sys
def handle_stdin(key, mask):
if key.data == 'quit':
sel.unregister(sys.stdin)
print("Closing due to 'quit'")
return False
else:
print(f"Received from stdin: {key.data}")
sock.sendto(key.data.encode(), (remote_host, remote_port))
return True
def handle_socket(key, mask):
data, addr = key.fileobj.recvfrom(4096)
print(f"Received message from {addr}: {data.decode()}")
key.fileobj.sendto(data, addr)
return True
def main():
selector = selectors.DefaultSelector()
std_in_key = selectors.SelectorKey(fileobj=sys.stdin, events=selectors.EVENT_READ, data='quit')
selector.register(std_in_key, handle_stdin)
remote_host = '127.0.0.1' # Replace with your server's IP address
remote_port = 12345 # Replace with the desired port
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('localhost', 0)) # Bind to a random available port
sock.setblocking(False) # Make it non-blocking
skey = selectors.SelectorKey(fileobj=sock, events=selectors.EVENT_READ | selectors.EVENT_WRITE, data=sock)
selector.register(skey, handle_socket)
while True:
events = selector.select(timeout=None)
for key, mask in events:
callback = key.data
callback(key, mask)
if __name__ == "__main__":
main()
#
阅读全文