B4R Question Ethernet Server Socket

Erel

B4X founder
Staff member
Licensed User
Longtime User
Full example:
B4X:
Sub Process_Globals
   Public Serial1 As Serial
   Private eth As Ethernet
   Private ethServer As EthernetServerSocket
   Private MacAddress() As Byte = Array As Byte(0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED)
   Private const serverPort As UInt = 51042
   Private astream As AsyncStreams
   Private bc As ByteConverter
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   If eth.InitializeDHCP(MacAddress) = False Then
     Log("Error connecting to network.")
     Return
   Else
     Log("Connected to network. My ip address: ", eth.LocalIp)
   End If
   ethServer.Initialize(serverPort, "ethServer_NewConnection")
   ethServer.Listen
End Sub

Sub ethServer_NewConnection (NewSocket As EthernetSocket)
   Log("New connection")
   astream.Initialize(NewSocket.Stream, "astream_NewData", "astream_Error")   
End Sub

Sub astream_NewData (Buffer() As Byte)
   Log("Received: ", bc.HexFromBytes(Buffer))
End Sub

Sub astream_Error
   Log("Error")
   ethServer.Listen 'need to call Listen after the connection broke.
End Sub

Note that the NewConnection event will only be raised after the client has send at least one byte.

You can test it with this B4J (non-ui) code:
B4X:
Sub Process_Globals
   Private sock As Socket
   Private astream As AsyncStreams
End Sub

Sub AppStart (Args() As String)
   sock.Initialize("sock")
   sock.Connect("192.168.0.40", 51042, 10000) 'change to Arduino ip
   StartMessageLoop
End Sub

Sub sock_Connected (Successful As Boolean)
   If Successful Then
     astream.Initialize(sock.InputStream, sock.OutputStream, "astream")
     astream.Write(Array As Byte(1, 2, 3, 4))
   End If
End Sub

Sub astream_NewData (Buffer() As Byte)
   
End Sub
 
Upvote 0

rdkartono

Member
Licensed User
Longtime User
Sorry for waking old thread, but is it possible for EthernetServerSocket to receive more than 1 connections ?
If not possible, then I need to create several EthernetServerSocket variables, with different listening port, right ? (One EthernetServerSocket for one connection only)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top