B4J Question ServerSocket and CloseExistingConnection

marcick

Well-Known Member
Licensed User
Longtime User
I have a server socket that listen for connection from more of 100 devices.
When a device connect to the server, it starts to send a data packet every 10 seconds.
If I call "CloseExistingConnection" in the code below, for each data packet the device need to reconnect and all becomes slower.
I see that not calling "CloseExistingConnection" all works better. When a device stops to send data, after a timeout the event "Astream_Terminated" is called.
Is it safe to work like this ?
Is there a limit on the number of connections that can be kept alive in the same moment ?
Where is declared the timeout ? I would like to keep it at 30 second sor so.

B4X:
Private Sub ListenForBls1Connections
    Do While working
        Bls1ServerSocket.Listen
        Wait For Server_NewConnection (Successful As Boolean, NewSocket As Socket)
        Log("new connection")
        If Successful Then
            'CloseExistingConnection
            Bls1client = NewSocket
            astream.Initialize(Bls1client.InputStream,Bls1client.OutputStream,"astream")
        End If
    Loop
End Sub
 
Last edited:

marcick

Well-Known Member
Licensed User
Longtime User
Yes, I did it now and seems to work fine.
I manage the Astream_Error and Astream_Terminated events to close the proper astream and socket.

The only point not very nice is that sometimes the connection is broken for timeout. The Astream_Error is correctly generated, but just before it I see this in the console :

B4X:
java.net.SocketTimeoutException: Read timed out
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at anywheresoftware.b4a.randomaccessfile.AsyncStreams$AIN.run(AsyncStreams.java:19
3)
        at java.lang.Thread.run(Unknown Source)
Astream_Error from [IsInitialized=true, IP=151.38.129.194, Sock=anywheresoftware.b4a.objec
ts.SocketWrapper@5ccddd20
]

This is the events code:

B4X:
Sub AStream_Error
    Dim astream As AsyncStreams = Sender
    Log("Astream_Error from " & ClientMap.GetDefault(Sender, "???"))
    'Log(LastException)
    Dim bc As Bls1Client=ClientMap.Get(Sender)
    astream.Close
    bc.Sock.Close
    ClientMap.Remove(Sender)
End Sub

Sub AStream_Terminated
    Dim astream As AsyncStreams = Sender
    Log("Astream_Terminated from " & ClientMap.GetDefault(Sender, "???"))
    Dim bc As Bls1Client=ClientMap.Get(astream)
    astream.Close
    bc.Sock.Close
    ClientMap.Remove(Sender)
End Sub

Looks like it's not possible to avoid that bad text in the console, right ?
 
Upvote 0
Top