UDP协议相比TCP要简单许多,虽然数据无法保证完整性.
先看一下client端的演示代码:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
port = 8000
host = '192.168.1.102'
while True:
msg = raw_input()
if not msg:
break
s.sendto(msg,(host,port))
s.close()
|
注意,在创建socket的时候,第二个参数要为SOCK_DGRAM,然后,我们只需要调用sendto即可以了,真是太方便了.
再看看server端代码:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('192.168.1.102',8000))
while True:
data,addr = s.recvfrom(1024)
if not data:
print 'client has exited!'
break
print 'received:',data,'from',addr
s.close()
|
创建socket后,然后bind至IP及端口.下一步在循环中接受数据.recvfrom的返回值包括两个,data是接受到的数据,addr是连接的client端的地址.真是太方便了.