相對TCP連接,UDP連接更加簡單
服務端,循環接收客戶端發來的消息,並將消息寫入一個文件中。
#udp socket
#filename udpServer.py
import socket
server=socket.socket(socket.AF_INET ,socket.SOCK_DGRAM )
#bind the port
server.bind(('',17800))
print 'udp server starts'
while True:
f=file('recv.txt','a')
data,(addr,port)=server.recvfrom(1024)
print data
#,addr,port
f.write(data)
f.close()
客戶端:向服務端發送一條消息,關閉。
#udp client
#file name udpClient.py
import socket
client=socket.socket(socket.AF_INET ,socket.SOCK_DGRAM )
client.sendto("hello python",('localhost',17800))
client.close()