[RTL8722CSM] [RTL8722DM] Socket - Echo Server and Client

Materials

  • AmebaD[AMB21 / AMB22] x 2

Steps

After WiFi is set up, the best way to access the internet is to use socket. Socket is like an imaginary ethernet socket by which you use to connect your PC to some server on the internet like Google or Github.

Application layer protocol like HTTP are also built on top of socket. Once you are given an IP address and a port number, you can start to connect to the remote device and talk to it.

image1

Here is an example of letting a server socket and a client socket to echo each other’s message, to use this example, you need 2 ameba RTL8722 running MicroPython, copy and paste the following code to 2 ameba respectively under REPL paste mode.

This is the server code,

 1import socket
 2from wireless import WLAN
 3wifi = WLAN(mode = WLAN.STA)
 4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
 5s = socket.SOCK()
 6port = 5000
 7s.bind(port)
 8s.listen()
 9conn, addr = s.accept()
10while True:
11  data = conn.recv(1024)
12  conn.send(data+"from server")

This is the client code,

 1import socket
 2from wireless import WLAN
 3wifi = WLAN(mode = WLAN.STA)
 4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
 5c = socket.SOCK()
 6# make sure to check the server IP address and update in the next line of code
 7c.connect("your server IP address", 5000)
 8c.send("hello world")
 9data = c.recv(1024)
10print(data)