B4J Question is it possible to make a ServerSocket run side by side with Jserver websocket ?

Waldemar Lima

Well-Known Member
Licensed User
Hi guys, I'm trying to create a class that instantiates a SocketServer in the same project as a JServer, but I can't create a listener that works...

code example >:

ServerSocket class
Sub Class_Globals
    Private cserver As ServerSocket
    Private astreams As AsyncStreams
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    Log("Server Socket running >: "&cserver.GetMyIP&":3556")
End Sub

private Sub cserver_NewConnection (Successful As Boolean, NewSocket As Socket)
    If (Successful = True) Then
        Log("Um usuario foi conectado")
        astreams.Initialize(NewSocket.InputStream,NewSocket.OutputStream, "astreams")
        Log("Erro ao conectar.")
    End If
End Sub

Sub astreams_Terminated
    Log("Baitola Desconectado.")
End Sub

Sub astreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF-8")
    Log("Msg recebida = "&msg)
End Sub

Main File
#Region Project Attributes
    #MergeLibraries: True
#End Region

Sub Process_Globals
    Private srvr As Server
    Private csrvr As ServerSocket
End Sub

Sub AppStart (Args() As String)
    srvr.Port = 51042
    srvr.StaticFilesFolder = File.Combine(File.DirApp, "www")
    srvr.AddHandler("/guessmynumber/guess", "GuessMyNumber", False)
    srvr.AddHandler("/guessmynumber/reset", "ResetMyNumber", False)
    srvr.AddWebSocket("/guessmynumber_ws/ws", "WSGuessMyNumber")
    Log("Server Websocket running >: "&""&srvr.Port)
    'open browser and navigate to:
End Sub

Is there a way to make both work side by side?


B4X founder
Staff member
Licensed User
Longtime User
It should work. What happens when you run it?

1. Note that if you don't call ServerSocket.Listen after the connection, the server will not listen for new connections.
2. With the current code, you will not be able to handle more than a single connection at a time.
Example of supporting multiple clients with sockets: https://www.b4x.com/android/forum/threads/mjpeg-cctv-server.73792/#content
Upvote 0