I'm trying to implement a simple web-server using NodeMCU. It's very simple, one connection at any time. I'm porting a project from regular arduino C to B4R. So right now just a simple, receive some data and send a response. With the following code, it all seems to work with the exception that AStream_Error event is always triggered for every connection. I can get data and respond okay but every time AStream_Error is triggered. I figured I could use LastException but that doesn't seem like it's availble in B4R - I am using v2.2. What am I missing?
I cobbled together this example from the forum and examples...thank you for any insight.
I cobbled together this example from the forum and examples...thank you for any insight.
B4X:
Private Sub AppStart
Dim ssid As String
Dim password As String
ssid = "xxx"
password = "xxx"
Serial1.Initialize(115200)
Log("AppStart")
pin5.Initialize(14, pin5.MODE_OUTPUT)
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
server.Initialize(80, "server_NewConnection")
server.Listen
'Timer1.Initialize("Timer1_Tick", 1000) '1000ms = 1 second
'Timer1.Enabled = True
End Sub
Sub Server_NewConnection (NewSocket As WiFiSocket)
Log("Client connected")
astream.Initialize(NewSocket.Stream, "astream_NewData", "astream_Error")
End Sub
Sub AStream_NewData (Buffer() As Byte)
Log("Received from server: ", Buffer)
'astream.Write("HTTP/1.1 200 OK").write(CRLF)
'astream.Write("Content-Type: text/html").Write(CRLF).Write(CRLF)
'astream.Write("<b>Hello World</b><br/><a href=""https://www.b4x.com"">B4X</a>")
Dim bc As ByteConverter
Dim s As String
s = "HTTP/1.1 200 OK\r\n"
Dim bytesa() As Byte
bytesa = bc.ObjectToBytes(s,s.Length)
astream.Write(bytesa)
s = "Content-Type: text/html\r\n"
bytesa = bc.ObjectToBytes(s,s.Length)
astream.Write(bytesa)
CallSubPlus("CloseConnection", 100, 0)
' Dim bc As ByteConverter
'Dim data As String
'data = bc.StringFromBytes(Buffer)
'Dim be(10) As Object
'Dim data() As Object = ser.ConvertBytesToArray(Buffer,be)
'Log("-------->Received:" + data)
'For Each o As Object In data
' Log(o)
'Next
End Sub
Sub CloseConnection(u As Byte)
Log("writing")
server.Socket.Stream.Flush
server.Socket.Close
End Sub
Sub AStream_Error
Log("Error")
server.Listen
End Sub