In this example one of the boards acts as an access point and a server and the other board connects to the server wifi network and to the server socket.
Note that for the client to be able to connect to the server socket it, its own access point must be disabled. This is done with this code:
There is also code in the server to set the wifi mode to AP (access point only). It is probably not required.
The server closes the socket after it receives the message. This is useful to allow new connections as disconnections are not immediately detected.
Server code:
Client code:
Note that for the client to be able to connect to the server socket it, its own access point must be disabled. This is done with this code:
B4X:
#if C
void SetSTA(B4R::Object* o) {
WiFi.mode(WIFI_STA);
}
#end if
There is also code in the server to set the wifi mode to AP (access point only). It is probably not required.
The server closes the socket after it receives the message. This is useful to allow new connections as disconnections are not immediately detected.
Server code:
B4X:
Sub Process_Globals
Public Serial1 As Serial
Private wifi As ESP8266WiFi
Private server As WiFiServerSocket
Private astream As AsyncStreams
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
Log(wifi.StartAccessPoint("esp_server"))
Log(wifi.AccessPointIp)
RunNative("SetAP", Null)
Log(wifi.AccessPointIp)
Log(wifi.LocalIp)
server.Initialize(51042, "server_NewConnection")
server.Listen
End Sub
#if C
void SetAP(B4R::Object* o) {
WiFi.mode(WIFI_AP);
}
#end if
Sub Server_NewConnection (NewSocket As WiFiSocket)
astream.InitializePrefix(NewSocket.Stream, False, "astream_NewData", "astream_Error")
Log("new connection")
End Sub
Sub astream_NewData (Buffer() As Byte)
Log("new data: ", Buffer)
server.Socket.Close 'disconnect to allow new connections
End Sub
Sub astream_Error
Log("error")
server.Listen
End Sub
Client code:
B4X:
Sub Process_Globals
Public Serial1 As Serial
Private wifi As ESP8266WiFi
Private socket As WiFiSocket
Private astream As AsyncStreams
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
RunNative("SetSTA", Null)
Log(wifi.Connect("esp_server"))
Log(wifi.LocalIp)
Connect(0)
End Sub
Sub Connect(u As Byte)
Log("Trying to connect")
If socket.ConnectIP(Array As Byte(192, 168, 4, 1), 51042) Then
Log("connected")
astream.InitializePrefix(socket.Stream, False, "astream_NewData", "astream_Error")
astream.Write("hello!!!")
Else
CallSubPlus("Connect", 1000, 0)
End If
End Sub
#if C
void SetSTA(B4R::Object* o) {
WiFi.mode(WIFI_STA);
}
#end if
Sub astream_NewData (Buffer() As Byte)
Log("new data: ", Buffer)
End Sub
Sub astream_Error
Log("error")
End Sub