2018年11月25日 星期日

用Python實作UDP通訊程式


接收端程式
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

PORT = 1060

s.bind(('192.168.1.8', PORT))
print('Listening for broadcast at ', s.getsockname())

while True:
    data, address = s.recvfrom(65535)
    print('Server received from {}:{}'.format(address, data.decode('utf-8')))

傳送端程式:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 1060
network = '192.168.1.8'
s.sendto('Client broadcast message!456'.encode('utf-8'), (network, PORT))

為了方便進行單機測式,我們使用cmd應用程式,開啟後先執行命令 

1. cd C:\Users\user\AppData\Local\Programs\Python\Python37
2. 輸入Python
3.再把接收端程式輸入在cmd應用程式端
4.然後再Python工具中執行傳送端的應用程式



沒有留言:

張貼留言