B4J Question i want MORE than one connection

ArminKH

Well-Known Member
hello here is my code
B4X:
'Non-UI application (console / server application)
#Region  Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
    #AdditionalJar: mysql-connector-java-5.1.35-bin.jar
#End Region

Sub Process_Globals
    Public ServerSocket1 As ServerSocket
    Dim SH As SocketHandler
        Private Socket1 As Socket
    Private AStreams As AsyncStreamsObject
    Dim timer1 As Timer
End Sub

Sub AppStart (Args() As String)
    SH.Initialize
    ServerSocket1.Initialize(51045,"ServerSocket1")
    ServerSocket1.Listen
    StartMessageLoop'only required in a console app
End Sub
Sub ServerSocket1_NewConnection (Successful As Boolean, NewSocket As Socket)
    If Successful Then
        Log("Connected")
        Socket1 = NewSocket

        AStreams.Initialize(Me,"AStreams")
        AStreams.Start(Socket1.InputStream,Socket1.OutputStream)
        SendMessage2Client
    Else
        Log(LastException.Message)
    End If
    ServerSocket1.Listen 'Continue listening to new incoming connections
End Sub

Sub AStreams_Terminated
    ServerSocket1.Listen
    Socket1.Close
    Socket1.Initialize("Socket1")
End Sub

Sub AStreams_NewObject(Key As String, Value As Object)
  
    Select Key
        Case "Image"
            Dim bmp As Image = Value
            Log("Received image")
        Case "Message"
            Dim message As String = Value
            Log("Received message: " & message)      
    End Select
End Sub

Sub AStreams_ObjectSent (Key As String)
    Log(Key & " Sent")
End Sub

Sub SendMessage2Client
timer1.Initialize("timer1",1000)
timer1.Enabled=True
'    AStreams.WriteObject("Message", "Hello From Server My frieandzzzzzzzzzz")
End Sub

Sub timer1_tick
    AStreams.WriteObject("Message", DateTime.Time(DateTime.Now))
End Sub
my server send time to client
but when a new device connected to server then my previeus connection closed and sending data to my first connected device stoped
tnx
 

Daestrum

Expert
Licensed User
Longtime User
It's probably because you keep overwriting socket1 every time you get a new connection.
When you get a new connection, stick it in a list, then in your timer_tiick routine, read the list and set the astreams to the socket from the list, send the data, then go to next item and repeat until you reach the end of the list.

(I am tired at present so it may not make sense when I read it tomorrow).
 
Upvote 0
Top