B4J Question TCP Server with multiple connections

aminoacid

Active Member
Licensed User
Longtime User
I have been experimenting with some TCP Server code that I extracted from an example that I found in this forum. It works great! However it is limited to one connection at a time. I'm trying to figure out how the server can handle multiple socket connections simultaneously. In VB you could create a Winsock control array and assign each connection to a separate socket when a connection is accepted. I don't see anything similar or any information on this site on doing something similar. Is this possible? Or is the TCP server limited to one connection at a time? Is there an example that I can look at? Thanks all ! Here is the complete code that I have working but it is limited to one connection:


TCP Server:
'Non-UI application (console / server application)
#Region Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
#End Region

Sub Process_Globals
    Private Lconnected As Boolean
    Private Lclient As Socket
    Public server As ServerSocket
    Private AST3 As AsyncStreams
    Private working As Boolean = True
    Dim timer1 As Timer
End Sub

Sub AppStart(Args() As String)
    server.Initialize(4040, "server")
    ListenForConnections
    Lconnected=False
    timer1.Initialize("Timer1",2000)
    timer1.Enabled=True
    StartMessageLoop
End Sub

Sub Timer1_tick
    Dim packet As String
    Dim wpkt() As Byte
    
    packet=" Hello "
    wpkt=packet.GetBytes("ASCII")
    
    If Lconnected Then
        Log(" Sending data ")
        Try
            AST3.Write(wpkt)
        Catch
            Log("Exeption")
        End Try       
    End If

End Sub

Private Sub ListenForConnections
    Do While working
        server.Listen
        Wait For Server_NewConnection (Successful As Boolean, NewSocket As Socket)
        If Successful Then
            CloseExistingConnection
            Lclient = NewSocket
            AST3.Initialize(Lclient.InputStream, Lclient.OutputStream, "AST3")
            Lconnected=True
            Log("Listening")
        End If
    Loop
End Sub


Sub CloseExistingConnection
    If AST3.IsInitialized Then AST3.Close
    If Lclient.IsInitialized Then Lclient.Close
    Lconnected=False
    Log("Connection Closed")
End Sub

Sub AST3_Error
    Lconnected=False
    Log("Error")
End Sub

Sub AST3_Terminated
    Lconnected=False
    Log("Terminated")
End Sub



Sub AST3_NewData (Buffer() As Byte)

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
    Log ("Application Error")
    Return True
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Is this possible?
Yes.

However it is easier to implement the network code in a class and create multiple instances of the class.

Two examples:
[B4X] FTP Server implemented with Socket and AsyncStreams
 
Upvote 0
Top