B4R Tutorial Simple example of how to have a TCP Server and make HTTP Client calls in same project

I thought I'd share this super simple example of creating a TCP Server and making very simple HTTP Client calls in same project. Typically most projects do one or the other and not both. Here you can see how fairly straight forward to setup both a TCP Server (in this example I have that configured in prefix mode as I am communicating with another B4J program across the network) and then also make a basic HTTP GET request with query string parameters/values.

The code below shows how to set it up and the timer is used to make HTTP GET requests every 5 seconds. The http URL line actually sends the esp8266 device ip on the query line.

This requires the RandomAccessFile and WIFI Libraries.

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.
    Public Serial1 As Serial
    Public Astream As AsyncStreams
    Private server As WiFiServerSocket
    Public Wifi As ESP8266WiFi
    Public ser As B4RSerializator

    Public socket As WiFiSocket
    Private Astream2 As AsyncStreams
    Private EOL() As Byte = Array As Byte(13, 10)

    Public eeprom As EEPROM
    Dim counter As UInt
    Dim Timer1 As Timer
   
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")

    ConnectToAccessPoint
    WifiServerStart

    Timer1.Initialize("Timer1_Tick", 5000) 'timer set to call client
    Timer1.Enabled = True 'don't forget to enable it

    ClientConnectToHTTPServerAndGetURL

End Sub


Private Sub Timer1_Tick
    counter  = counter + 1
    Log("Counter:"     , counter) ', " wifistatus:" , wifistatus)

    Dim header() As Byte = eeprom.ReadBytes(0, 0)
    ClientConnectToHTTPServerAndGetURL
End Sub

Private Sub ConnectToAccessPoint
    Dim ssid As String
    Dim password As String

    ssid = "accesspoint-ssid"
    password = "secretpassword"
   
    If Wifi.Connect2(ssid,password) Then 'change to your network SSID (use Connect2 if a password is required).
        Log("----Connected to wireless network."  + ssid)
        Log("----My ip: ", Wifi.LocalIp)
    Else
        Log("Failed to connect.")
        Return
    End If

End Sub

private Sub WifiServerStart
   
    server.Initialize(51042, "server_NewConnection")
    server.Listen

End Sub

Private Sub Server_NewConnection (NewSocket As WiFiSocket)
    Log("+++New connection+++")

    Astream.InitializePrefix(NewSocket.Stream, False, "astream_Server_NewData", "astream_Server_Error")
    'Astream.Initialize(NewSocket.Stream, "astream_NewData", "astream_Error")

End Sub

Private Sub Astream_Server_NewData (Buffer() As Byte)
    Log(Buffer)

    Log("Data received on server.")
    Dim byte_buffer() As Byte

    byte_buffer = ser.ConvertArrayToBytes(Array As Object("DONE"))
    Astream.Write(byte_buffer)
    server.Socket.Stream.Flush
    server.Socket.Close
End Sub

Private Sub AStream_Server_Error
    Log("Disconnected")
    server.Socket.Close
    server.Listen
End Sub

Private Sub ClientConnectToHTTPServerAndGetURL()

    socket.Close

    Dim st As Stream = Null
    'Dim host As String = "10.0.0.200"
    Dim port As UInt = 17178

    If socket.ConnectIP(Array As Byte(10,0,0,200),port) Then
        st = socket.Stream
    End If

    If st = Null Then
        Log("SendRequest failed to connect.")
        Return
    End If

    Log("Connected to HTTP Server")
    Astream2.Initialize(st, "Astream_Client_NewData", "Astream_Client_Error")

    Dim url_payload As String = JoinStrings(Array As String("GET /device?ip=",Wifi.LocalIp,"&count=",counter," HTTP/1.1"))
   
'the above is the equivalent to: HTTP://10.0.0.200/device?ip=10.0.0.30&count=1" for example 

    Astream2.Write(url_payload).Write(EOL)
    Astream2.Write("Host: foobar.com").Write(EOL)
    Astream2.Write("Connection: close".GetBytes).Write(EOL)
    Astream2.Write(EOL)

    socket.Stream.Flush
    socket.Close
End Sub

Private Sub AStream_Client_NewData (Buffer() As Byte)
    Log(Buffer)
End Sub

Private Sub AStream_Client_Error

End Sub
 
Top