#Region Service Attributes
#StartAtBoot: False
#ExcludeFromLibrary: True
#End Region
Sub Process_Globals
Public connected As Boolean
Private client As Socket
Public server As ServerSocket
Private astreams As AsyncStreams
Private const PORT As Int = 40640
Private working As Boolean = True
End Sub
Sub Service_Create
server.Initialize(PORT, "server")
ListenForConnections
End Sub
Private Sub ListenForConnections
Do While working
server.Listen
Wait For Server_NewConnection (Successful As Boolean, NewSocket As Socket)
If Successful Then
CloseExistingConnection
client = NewSocket
If astreams.IsInitialized Then astreams.Close
astreams.Initialize( NewSocket.InputStream, NewSocket.OutputStream,"NewSocket")
UpdateState(True)
End If
Loop
End Sub
Sub Service_Start (StartingIntent As Intent)
End Sub
Public Sub ConnectToServer(Host As String)
Log("Trying to connect to: " & Host)
CloseExistingConnection
Dim client As Socket
client.Initialize("client")
client.Connect(Host, PORT, 10000)
Wait For Client_Connected (Successful As Boolean)
If Successful Then
astreams.Initialize(client.InputStream,client.OutputStream, "astream")
UpdateState (True)
Else
Log("Failed to connect: " & LastException)
End If
End Sub
Public Sub Disconnect
CloseExistingConnection
End Sub
Sub CloseExistingConnection
If astreams.IsInitialized Then astreams.Close
If client.IsInitialized Then client.Close
UpdateState (False)
End Sub
Sub UpdateState (NewState As Boolean)
connected = NewState
CallSub(JSON, "SetState")
End Sub
Sub AStreams_Error
UpdateState(False)
End Sub
Sub AStreams_Terminated
UpdateState(False)
End Sub
Sub AStreams_NewData (Buffer() As Byte)
Log("NewData")
CallSub2(JSON, "NewData", Buffer)
End Sub
Public Sub SendData (data As String)
Dim bc As ByteConverter
Log("Send data")
Log(bc.StringToBytes(data,"UTF-8"))
If connected Then astreams.Write(bc.StringToBytes(data,"UTF-8"))
End Sub
'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub