UDP 套接字可以在两种不同的模式下运行:
- 默认未连接模式:接收所有发送到您进程的端口/地址的数据报;您需要为每次发送指定目标地址。
- 连接模式:仅接收从您连接的地址/端口发送的数据报;您无需在每次发送时指定目标地址。
这是对已连接的 UDP 套接字的一个小回顾。
编辑:
这是一个小的 python UDP 服务器,它接受来自任何客户端的数据包并将它们复制到第二个服务器。一切都通过一个未连接的 UDP 套接字完成。
#!/usr/bin/env python
import sys, socket, string
if len( sys.argv ) != 4:
print "Usage: udptee <local-listen-port> <copy-host> <copy-port>"
exit( 1 )
copy = ( sys.argv[2], int( sys.argv[3] ))
s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
#s.bind(( 'localhost', int( sys.argv[1] )))
s.bind(( '', int( sys.argv[1] )))
print "listening on ", s.getsockname()
print "copying to", copy
while True:
line, addr = s.recvfrom( 1024 )
print "received: ", line, " from ", addr
s.sendto( line, addr ) # echo to source
s.sendto( line, copy ) # copy to tee
if string.strip( line ) == "exit": break
print "Goodbye and thanks for all the fish"
s.close()
在一个终端中运行它:
~$ ./udptee 9090 <IP-of-copy-server> 9999
然后netcat
在第二学期以服务器模式开始。这个将接受数据报的副本:
# this used to be "nc -ul 127.0.0.1 9999" which only listened on loopback
~$ nc -ul 9999
在第三学期启动netcat
客户端以将内容发送到第一台服务器:
~$ nc -u <IP-of-tee-server> 9090
开始输入并看到两个服务器都回显您输入的内容。