B4J Question how to: BIDIRECTIONAL SOCKET

paul fredrick

Member
Licensed User
Longtime User
where can I find examples to create a service that can receive and send json via socket?
Thank you
 

paul fredrick

Member
Licensed User
Longtime User
thanks, I have tried the various examples with success, but I would need to get a multiple and simultaneous connection of N clients to 1 server.
it's possible?
how?
thank you
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
see: Server B4J.
As it is based on AsyncStreams and it can handle multiple concurrent connections.
 
Upvote 0

paul fredrick

Member
Licensed User
Longtime User
thanks for the replies, but that's not exactly what i'd like to get.
based on Erel's example, https://www.b4x.com/android/forum/t...-asyncstreams-b4xserializator.119011/#content
I have adapted some things to my needs.
1) I declare the PORT - SERVER - CLIENT - STREAM:
B4X:
Private client1 As Socket
Private client2 As Socket
Public server1 As ServerSocket
Public server2 As ServerSocket
Private astream1 As AsyncStreams
Private astream2 As AsyncStreams
Private const PORT1 As Int = 50001
Private const PORT2 As Int = 50002
etc...
2) I initialize the PORT and put them in listening
B4X:
server1.Initialize (PORT1, "server1")
ListenForConnections1
server2.Initialize (PORT2, "server2")
ListenForConnections2
etc...
3) I create the SUB
B4X:
Private Sub ListenForConnections1
Do While working
server1.Listen
Wait For Server1_NewConnection (Successful As Boolean, NewSocket1 As Socket)
If Successful Then
client1 = NewSocket1
astream1.InitializePrefix (client1.InputStream, False, client1.OutputStream, "astream")
connected = True
End If
Loop
End Sub
Private Sub ListenForConnections2
Do While working
server2.Listen
Wait For Server2_NewConnection (Successful As Boolean, NewSocket2 As Socket)
If Successful Then
client2 = NewSocket2
astream2.InitializePrefix (client2.InputStream, False, client2.OutputStream, "astream")
connected = True
End If
Loop
End Sub
etc...
4) I identify the origin in the stream, where nrClient is a data that comes from the client
B4X:
Public Sub SendData (data () As Byte)
If nrClient = 1 Then
If connected Then astream1.Write (data)
End If
If nrClient = 2 Then
If connected Then astream2.Write (data)
End If
End Sub
5) finally send with SEND_ACTION

everything works...
but if i had 20 clients, i would have to multiply everything
my question is
are there better solutions to achieve the same result?

Thanks again
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…