This example uses an Ethernet shield to connect to a server. In this case the server is implemented with B4J, though you can easily implement a similar server with B4A or B4i.
Whenever the user clicks on a connected button the event will be sent to the server.
The first step is to connect to the network.
We can assign a static address to the board or ask the network DHCP service to assign an address automatically.
MacAddress is a 6 bytes array with the device mac address. On some boards the address is written on the board. You can use any valid value you like. Just make sure that it is unique in the local network.
The next step is to connect to the server with an EthernetSocket object:
This code will try to connect. If it fails it will try again after one second.
The AsyncStreams object is initialized after a successful connection.
Sending the data:
AsyncStreams events:
The B4J code (non-ui program):
The B4R program is attached.
Whenever the user clicks on a connected button the event will be sent to the server.
The first step is to connect to the network.
We can assign a static address to the board or ask the network DHCP service to assign an address automatically.
B4X:
'eth is an Ethernet object.
If eth.InitializeDHCP(MacAddress) = False Then
Log("Error connecting to network.")
Return
End If
The next step is to connect to the server with an EthernetSocket object:
B4X:
Sub Connect(unused As Byte)
If ethClient.ConnectIP(serverIp, serverPort) = False Then
Log("trying to connect again")
CallSubPlus("Connect", 1000, 0)
Return
End If
Log("Connected to server")
astream.Initialize(ethClient.Stream, "Astream_NewData", "Astream_Error")
End Sub
The AsyncStreams object is initialized after a successful connection.
Sending the data:
B4X:
Sub Btn_StateChanged (State As Boolean)
If ethClient.Connected Then
Dim s As Byte
If State Then s = 1 Else s = 0
astream.Write(Array As Byte(s))
End If
End Sub
AsyncStreams events:
B4X:
Sub Astream_NewData (Buffer() As Byte)
Log("Received from server: ", Buffer) 'pass the array of bytes. Don't convert to string.
End Sub
Sub Astream_Error
Log("error")
ethClient.Close
CallSubPlus("Connect", 1000, 0) 'try to reconnect
End Sub
The B4J code (non-ui program):
B4X:
Sub Process_Globals
Private astream As AsyncStreams
Private server As ServerSocket
End Sub
Sub AppStart (Args() As String)
server.Initialize(51042, "server")
server.Listen
StartMessageLoop
End Sub
Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)
Log("new connection")
astream.Initialize(NewSocket.InputStream, NewSocket.OutputStream, "Astream")
server.Listen
End Sub
Sub Astream_NewData (Buffer() As Byte)
If Buffer(0) = 0 Then
Log("Button is down.")
Else
Log("Button is up.")
End If
astream.Write("Thank you for this useful information.".GetBytes("UTF8"))
End Sub
The B4R program is attached.
Attachments
Last edited: