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
B4X:
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
  
    cserver.Initialize(3556,"cserver")
    cserver.Listen
  
    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")
    Else
        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
B4X:
#Region Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
#End Region

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

Sub AppStart (Args() As String)
  
    srvr.Initialize("srvr")
    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")
    srvr.Start
    Log("Server Websocket running >: "&"127.0.0.1:"&srvr.Port)
  
    csrvr.Initialize
  
    StartMessageLoop
    'open browser and navigate to: http://127.0.0.1:51042/
End Sub

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

Erel

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
Top