B4J Question ServerSocket and Multi Client Problem

Arya8867

Member
Hi
I create a ServerSocket and connect with two client to server
I can send messages from clients to server, but i can't find who is sending the message and can't answer to client!
is there any way that astreams_NewData event show sender socket object?
 

Arya8867

Member
I find a way, but it's not professional and not good for many clients:

B4X:
Sub Process_Globals
   
    Dim Server As ServerSocket
        Private astream2 As AsyncStreamsText
    Dim websockets(6) As Socket
    Dim i As Int =0

End Sub

Sub AppStart (Form1 As Form, Args() As String)
    Server.Initialize(12345,"server")
    Server.Listen
End Sub

Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then   
        astream2.Initialize(Me,"astreams" & i ,NewSocket.InputStream,NewSocket.OutputStream,NewSocket)
        websockets(i)=NewSocket
    End If
    i = i+1
    Server.Listen
End Sub

Private Sub astreams0_NewData (Buffer() As Byte)
    Log(websockets(0).RemoteAddress & " : " & Buffer)
End Sub
Private Sub astreams1_NewData (Buffer() As Byte)
    Log(websockets(1).RemoteAddress & " : " & Buffer)
End Sub
Private Sub astreams2_NewData (Buffer() As Byte)
    Log(websockets(2).RemoteAddress & " : " & Buffer)
End Sub
Private Sub astreams3_NewData (Buffer() As Byte)
    Log(websockets(3).RemoteAddress & " : " & Buffer)
End Sub
Private Sub astreams4_NewData (Buffer() As Byte)
    Log(websockets(4).RemoteAddress & " : " & Buffer)
End Sub
Private Sub astreams5_NewData (Buffer() As Byte)
    Log(websockets(5).RemoteAddress & " : " & Buffer)
End Sub
]
 

Erel

Administrator
Staff member
Licensed User

Arya8867

Member
This is indeed not the correct approach.

You should implement the communication code in a class and create a class instance for each connection.

Example 1: https://www.b4x.com/android/forum/threads/mjpeg-cctv-server.73792/#content

Example 2: [B4X] FTP Server implemented with Socket and AsyncStreams

However a better solution is to use MQTT or jServer and build a real server.
thanks for your info
I need a persistent connection for two way communication
I think jServer doesn't support it and MQTT need two app(A broker and a server app)
 

Erel

Administrator
Staff member
Licensed User
I need a persistent connection for two way communication
I think jServer doesn't support it and MQTT need two app(A broker and a server app)
1. jServer supports it. You should use a WebSocket handler.
2. MQTT doesn't need two apps. You can run the broker inside the B4J app.
 
Top