Build a TCP chat service¶
Overview¶
This is a low-code walkthrough that uses the Ballerina Integrator TCP service and messaging capabilities to build an end-to-end real-time communication pipeline — without writing code by hand. You will:
- Create a TCP listener service that listens for incoming client connections on port
3000. - Register client usernames and maintain active client connections.
- Send and receive messages between the chat service and connected clients.
- Handle client disconnections and manage the client connection lifecycle.
Why this use case¶
- Demonstrates real-time bidirectional communication using TCP sockets.
- Shows how to manage multiple concurrent client connections and sessions.
- Illustrates data transformation between byte arrays and strings in network communication.
- Scales easily from a single client to multiple concurrent users.
Prerequisites¶
Before you begin, make sure you have the following:
- Visual Studio Code: Install Visual Studio Code if you don't have it already.
- WSO2 Integrator: BI Extension: Install the WSO2 Integrator: BI extension. For detailed steps, see Install WSO2 Integrator: BI.
- TCP Client Tools: Netcat (
nc) or Telnet for testing the chat service.
Step 1: Create a new integration project¶
WSO2 Integrator: BI extension provides a low-code graphical environment to visually design and deploy integrations using Ballerina.
-
Launch VS Code and click the WSO2 Integrator: BI icon on the left sidebar. You'll be taken to the welcome page that introduces the integration workspace.
-
Below the Get Started Quickly section, you'll see three separate options:
- Create New Integration – start a new integration project from scratch using the graphical designer.
- Import External Integration – bring in existing integrations from other platforms.
- Explore Pre-Built Samples – open existing templates or tutorials.
-
Click Create New Integration. This opens the integration creation wizard, where you can:
- Enter
TCP chat servicein Integration Name and choose a folder in Select Path.
- Enter
-
Once the project is created, you'll enter the graphical integration designer view. From here, you can start adding listeners, data mappings, and logic components to build your flow visually.
This is the entry point for all low-code projects in WSO2 Integrator: BI.
Step 2: Create the TCP service¶
In this step, you will add a TCP Service to your integration to handle TCP client connections on a specific port.
- In the Design view, click + Add Artifact.
- Under the Integration as API section, select TCP Service.
- In the Create TCP Service form, enter
3000in the TCP Port field. - Click Create.
The Service Designer will now load, displaying the TCP Service with the default
onConnectevent handler.
Step 3: Rename the service and add a class variable¶
- In the Types section, right-click the existing service type (shown as
TcpEchoService), and then select Edit to open the Service Class Designer. - Select the Edit (pencil) icon next to the Class Name box.
- Replace
TcpEchoServicewithChatService, and then select Save. - In the Class Variables section, select Add Variable (+).
- In the Add Variable dialog box, configure the following settings:
- Variable Name: Enter
username. - Variable Type: Select string.
- Default Value: Enter
""to initialize the variable as an empty string.
- Variable Name: Enter
- Select Save to add the variable to the list.
Step 4: Implement the onConnect logic¶
Declare the welcome prompt variable¶
- In the Service Class Designer, locate the Methods section, and then select the Edit (pencil) icon next to onConnect.
- On the flow diagram, hover over the connection line and select Add (+) to insert a new node.
- From the palette, select Declare Variable.
- In the Declare Variable properties, configure the following settings:
- Name: Enter
welcomePrompt. - Type: Select string.
- Expression: Enter
"Enter your username: "(include the double quotes).
- Name: Enter
- Select Save.
Send the prompt to the caller¶
- Select Add (+) on the flow line immediately after the
welcomePromptvariable. - In the Connections section of the palette, select caller.
- Select writeBytes from the list of operations.
- In the Data field, enter
welcomePrompt.toBytes(). - Select Save.
Update the return statement¶
- Select the Return node at the end of the flow.
- In the Expression field, replace the existing value with
new ChatService(). - Select Save to complete the function.
Step 5: Convert incoming bytes to string¶
Add a function call node¶
- Click Call Function in the right-side palette.
Select the conversion function¶
- Search for "string" in the function library panel.
- Select fromBytes from the list.
Configure the function parameters¶
- Enter
datain the bytes field. - Enter
messageResultin the Result field. - Click Save.
Step 6: Declare a variable for the message¶
Add a variable node¶
- Click Declare Variable in the right-side palette.
Configure the variable details¶
- Enter
messagein the Name field. - Select
stringas the Type. - Enter
messageResult.trim()in the Initial Value field. - Click Save.
Step 7: Handle new user registration¶
Add a conditional check¶
- Click If in the right-side palette.
- Enter
self.username == ""in the Condition field. - Click Save.
Add the update logic¶
- Drag the Update Variable node inside the If block to set the username.
Step 8: Assign the username¶
Add the update logic¶
- Click the + icon inside the If block.
- Select Update Variable from the list.
Configure the variable update¶
- Enter
self.usernamein the Variable field. - Enter
messagein the Expression field. - Click Save.
Step 9: Log the new client connection¶
Add the log node¶
- Click the + icon inside the If block.
- Select Log Info from the list.
Configure the log expression¶
- Click Expression in the properties panel.
- Enter
string ${self.username} connectedin the field. - Click Save.
Step 10: Log the welcome message¶
Add the log node¶
- Click the + icon inside the If block.
- Select Log Info from the list.
Configure the log expression¶
- Select Expression in the properties panel.
- Enter the string
string Welcome ${self.username}.toBytes()in the field. - Click Save.
Step 11: Prompt the user for input¶
Add the write action¶
- Select the + icon inside the If block.
- Select caller from the Connections menu.
- Select writeBytes from the list of actions.
Configure the prompt message¶
- Enter the following expression in the data field:
string Welcome ${self.username}! Enter your message:.toBytes(). - Select Save.
Step 12: Terminate the execution flow¶
Add the return statement¶
- Click the + icon in the flow.
- Select Return from the Control.
- Click Save.
Step 13: Log the chat message¶
Add the log node¶
- Select Log Info from the Logging section in the right-side palette.
Configure the log message¶
- Select Expression in the properties panel.
- Enter the string
string ${self.username}: ${message}in the field. - Select Save.
Step 14: Send an acknowledgment to the client¶
Add the write action¶
- Select the + icon at the bottom of the main flow, after the Log Info node.
- Select caller from the Connections list.
- Select writeBytes from the list of actions.
Configure the acknowledgment message¶
- Enter
string Sent: ${message}. Enter your next message:.toBytes()in the data field. - Select Save.
Step 15: Run and test the application¶
Run the application¶
- Select the Run icon (green play button) in the top-right corner of the editor to start the service.
- Wait for the terminal to indicate that the service is running.
Test the chat flow¶
- Open a new terminal window.
- Enter
telnet localhost 3000to connect to the chat service. - When the connection is established, enter a username (e.g.,
User1). - Verify that you receive the welcome message:
Welcome User1! Enter your message:. - Enter a chat message (e.g.,
Hello World). - Verify that you receive the acknowledgment:
User1: Hello World.
Note
You have successfully created a TCP chat service that can handle multiple concurrent client connections in real time.