網絡編程--python 實現簡單的UDP客戶端和服務端

相對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()


發佈了20 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章