B4J Tutorial How create a Chat using B4J and Server Composer [ Socket ]

Waldemar Lima

Active Member
Licensed User
hello everyone !

It is with great honor that I present to you my tool for creating websocket & socket servers, it was developed using C ++ [libwebsocket, enet, winsock, lua_wrapper, scintilla and others].

Today I will do a tutorial on how to use B4J with ServerComposer BUY HERE

*
First we need to open ServerComposer and create a new project., like the image below .


after creating the project, the IDE will write the default code, as in the image below.



now create a new B4J project [GUI] , after that, replace all default code to this code below and then save it. Required Libraries [ jCore ; jFX ; jNetwork & JRandomAccessFile ].

B4X:
#Region  Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

Sub Process_Globals
    Private fx As JFX
    Public MainForm As Form
    Private btnSend As Button
    Private Label1 As Label
    Private txtLogs As TextArea
    Private txtMessage As TextField
    Type Message (Body As String, From As String)
    Private astream As AsyncStreams
    Private Connection As Socket
    Private Label1 As Label
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.SetFormStyle("UNIFIED")
    MainForm.RootPane.LoadLayout("1") 'Load the layout file.
    MainForm.Show
    Connection.Initialize("Connection")
    Connection.Connect("127.0.0.1",5562,10000)
    
    Wait For Connection_Connected (Successful As Boolean)
    If Successful Then
        astream.Initialize(Connection.InputStream,Connection.OutputStream,"AStream")
    Else
        Log("Failed to connect: " & LastException)
        ExitApplication
    End If
    
End Sub

Sub AStream_NewData (Buffer() As Byte)
    
    Dim tempmsg As String
    tempmsg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Dim msg() As String
    msg = Regex.Split(":", tempmsg)
     Log(msg(0))
    If (msg(0) = "connected") Then
        Label1.Text = "Connected Users : "&msg(1)
    else if (msg(0) = "log") Then
            txtLogs.Text = txtLogs.Text & msg(1) & " says " & msg(2) & Chr(10)
    End If
    
End Sub

Sub btnSend_Click
    
    Log("enviando ...")
    Dim MyMessage As String = txtMessage.Text
    Dim bytes() As Byte = MyMessage.GetBytes("UTF-8")
    astream.Write(bytes)

End Sub

Sub AStream_Error
    ExitApplication
End Sub

Sub AStream_Terminated
    ExitApplication
End Sub
** Make sure all the syntax is without any errors in your project.

After doing this, go back to the ServerComposer IDE and replace all the default code with the following:

B4X:
function OnStart()
-- Function called when the server starts.
    PrintN("Server initialized on port : "..Core_ServerPort)
end

function OnConnect()
-- Function called when a client is connected .
    PrintN("A user has connected : ["..GetEventClient().."]")
    SetGlobalVariable(Var_Int,"connected",GetGlobalInt("connected")+1)
    SendMessageToAll("connected:"..GetGlobalInt("connected"))
    PrintN("Amount: "..GetGlobalInt("connected"))
end

function OnData()
-- Function called when the server receive message from client .
    PrintN("Message received : "..GetMessage().." from ["..GetEventClient().."]")
    SendMessageToAll("log:".."["..GetEventClient().."] : "..GetMessage())
end

function OnDisconnect()
-- Function called when a client is disconnected .
    PrintN("A user has disconnected : ["..GetEventClient().."]")
    SetGlobalVariable(Var_Int,"connected",GetGlobalInt("connected")-1)
    SendMessageToAll("connected:"..GetGlobalInt("connected"))
end
After pasting the code in ServerComposer, save the project.

Now we should export the server and run it.

To export your server, go to the top menu, and click "Compiler-> Compile and Run". Will open a new window.



In "Server Type:", select Socket , the operating system and protocol will be selected automatically (select manually if this does not happen), and finally in "Server Port:" type: 5562 .

Click Export Server, wait for the server to run!



Enjoy :D

Thank you all for your attention! And thank @Erel for permission to post the tutorial with my product :)
 
Top