WiFi網路溝通最簡單的就是使用Socket來進行點對點的溝通,想要知道你搭建的Server和client有沒有正確的運作,就可以找來兩個可以使用WiFi的設備,讓他們之間互聯并且echo(回應同樣的資訊)彼此的資訊來做驗證,以下就是上手啦,
材料準備
RTL8722 x 2
范例說明
WiFi連接完成后即可使用 Socket 來使用網路。 Socket 就像一個假想的乙太網路介面,你可以用它把你的 PC 連接到互聯網上的服務器上,比如 Google 或 Github。即使是像 HTTP 這樣的應用層協議也是建立在 socket 之上的。一旦給定了 IP 地址和埠號,就可以自由地連接到遠程設備并與其進行通信。連接流程如下圖所示。

下面是一個使用服務器socket和客戶端socket互相傳送訊息的范例,要使用這個范例,您需要兩個 RTL8722 來運行 MicroPython,在 REPL 的復制粘貼模式下分別將下面的代碼復制并粘貼到兩個 RTL8722。
以下是服務器代碼
import socket
from wireless import WLAN
wifi = WLAN(mode = WLAN.STA)
wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
s = socket.SOCK()
port = 5000
s.bind(port)
s.listen()
conn, addr = s.accept()
while True:
data = conn.recv(1024)
conn.send(data+"from server")
以下是客戶端代碼
import socket
from wireless import WLAN
wifi = WLAN(mode = WLAN.STA)
wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
c = socket.SOCK()
# make sure to check the server IP address and update in the next line of code
c.connect("your server IP address", 5000)
c.send("hello world")
data = c.recv(1024)
print(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/282960.html
標籤:單片機/工控
上一篇:AD 匯入drill檔案報錯Error: Line no. 233 - - Invalid tool number definition: T0, the a
下一篇:測量技術