B4J Question Multiples connections socket

victormedranop

Well-Known Member
Licensed User
HI I am trying to create a socket server in B4J. only to receive some data.
but I don't understand why is only permitting only one connection. I post my code
any help will by appreciated. is a non UI application.

B4X:
'Non-UI application (console / server application)

#Region Project Attributes

#CommandLineArgs:

#MergeLibraries: True

#AdditionalJar: mysql-connector-java-5.1.27

#End Region



Sub Process_Globals

Dim AStreams As AsyncStreams

Dim server As ServerSocket

Dim Socket1 As Socket

End Sub



Sub AppStart (Args() As String)

Log(server.GetMyIP)

server.Initialize(12345,"server")

server.Listen

StartMessageLoop

End Sub



'Return true to allow the default exceptions handler to handle the uncaught exception.

Sub Application_Error (Error As Exception, StackTrace As String) As Boolean

Return True

End Sub



Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)

If Successful Then

Log("Connected")

Socket1 = NewSocket

AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")

Else

Log(LastException.Message)

End If

End Sub



Sub AStreams_NewData (Buffer() As Byte)

Dim msg As String

msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")

readData(msg)

End Sub



Sub AStreams_Error

Log(LastException.Message)

Log("AStreams_Error")

End Sub



Sub AStreams_Terminated

Log("AStreams_Terminated")

End Sub



Sub readData(data As String)

If data.StartsWith("NB3") Then

Dim result() As String

result = Regex.Split(",",data)

For x=0 To result.Length -1

Log(result(x))

Next

Else

End If

End Sub
 

Daestrum

Well-Known Member
Licensed User
Not 100% certain, but I think having Socket1 as a global variable wont help, as each new connection will use the same socket.

You could probably change
B4X:
Socket1 = NewSocket
AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")
to
B4X:
AStreams.Initialize(NewSocket.InputStream, NewSocket.OutputStream, "AStreams")
but as I said, not 100% sure it would make a difference.
 
Top