- 你不关心消息是否丢失;
- 你不想要终止程序只是因为消息无法传递;
#!/usr/bin/env python # -*- coding: utf-8 -*- # server.py import socket port = 8081 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", port)) print "waiting on port:", port while 1: data, addr = s.recvfrom(1024) print data # client.py import socket port = 8081 host = "localhost" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) s.sendto("Holy Guido! It's working.", (host, port))
还有一个提醒事项,不要用上面的程序发送大量的数据包,尤其是在 Windows 上。要是想要发送大的消息的话,你可以这样做:
BUFSIZE = 1024 while msg: s.sendto(msg[:BUFSIZE], (host, port)) msg = msg[BUFSIZE:]