The WebSocket protocol (WS) provides the ability to exchange data between a browser and a server over a persistent connection. Data is transmitted through it in both directions in the form of "packets" without breaking the connection and additional HTTP requests.

WebSocket is good for constant communication services, such as chat rooms, online games, real-time marketplaces, etc.

As an example, let's create a backend for a simple chat. It is necessary to provide the basic features:

  1. Sending messages to chat.
  2. Determining the authorship of the message.
  3. Action notifications. For example, a new member joining the chat, leaving the chat, typing indicator (someone is typing...)

Database model

Let's start by creating a model for the database. Even if we do not initially plan to store messages and correspondence history in the database, we still need a model to structure sending messages and notifications.

Let's create a generic chat_event model that contains:

  1. Relation with the user. Any message includes information about which user it refers to.
  2. Type (enum) field with 4 possible options. Connected and Disconnected - for notifications when a user is connected or disconnected. Typing - to convey information that the user is currently writing a new message. Message - for a standard text message.
  3. Message (text) - the text of the message.


Endpoint configuration

The next development step is slightly different from the standard approach that is common to other features of the application. Usually, a business process is created, and then an endpoint is configured to run it. In the case of WebSockets, everything happens differently, and the starting point is the creation of an endpoint based on the triggers of which business processes are further created.

We need an endpoint section. There we create a new endpoint by selecting the appropriate option - WebSocket Endpoint.


For WebSockets there is no choice of request method - it is always GET. Let's specify a simple URL - /chat/ and create a group for it with the same name.

Next, we need to create variables that will determine the data exchange format within the WebSocket.

  • Client-to-Server. Similar to incoming parameters for standard business processes. In our example, we will create a simple text variable message (we will send ordinary text messages to the server).
  • Server-to-Client. Here variables are created for server messages, sending data from the server to the user. Note that this is not the same as a response to a user request. And although it can be sent as a reaction to user actions, it is more often caused by some external events. In our example, the server will send notifications of all events in the chat, so we will set the chat_event model as a variable.


After creating the variables, you can proceed to the main thing - creating the logic of the WebSocket. It is based on triggers that fire when a new message is received on a WebSocket, as well as when a connection is established or disconnected.


Creating a business process

Let's use the connect trigger and create a business process for it. It will be launched at the moment when the user establishes a connection with the WebSocket, and its task will be to send a notification about this to all connected users.

Note that the start block includes two parameters: User ID and Connection ID. Thus, you can not only immediately determine the user who established the connection but also get a unique identifier for this connection. In the future, this identifier can be used, for example, to send targeted messages or to terminate the connection forcibly.

Сreate all the necessary steps of the business process:

  1. Make User. Let's use the starting parameter User ID to create a user model.
  2. Make chat_event. Сreate an event notification model. We will connect it to the user using the model created in the previous step and also select the event type and set Type = Connected. We do not use the message parameter since, in this case, it is not a message that is transmitted but a connection notification.
  3. WSS Connections /chat/. Using this block, we will get a list of all active WebSocket connections.
  4. For Each Loop. We use the connections array as a loop parameter, sending notifications to each connected user.
  5. Expand WebSocket Connection. Expand the connection information to get the Connection ID.
  6. WSS Send /chat/. We use the Connection ID and the generated chat_event to send the notification.


Using Postman to test WebSockets

At this stage, the WebSocket, although it does not have significant functionality, is already operational and can be tested in practice. To do this, you can use any tool that allows you to work with WebSockets. Let's take a look at how to do this with Postman as an example.

Should click the New button and select WebSocket Request


You need to specify the URL for the WebSocket. It can be found using Swagger, where the WebSocket is in the list with the rest of the endpoints.


Unlike standard requests, WebSockets operate using the wss protocol, so you need to replace https with wss. The result should be a similar URL: wss://qvlxglh-app.apms.io/api/chat/

Next, you need to add an authentication token to the request since the connection cannot be anonymous. You need to create an Authorization header with a value like Bearer lBCiunRWg6BfogDrLml4jrC4iJiWucKo. Instead of lBCiunRWg6BfogDrLml4jrC4iJiWucKo, you need to insert your own token, which can be obtained as a result of authorization (POST /auth/ endpoint).


If everything is done correctly, then by clicking on the Connect button, a connection will be established, and the first message will be received from the server side, the business process for sending which was created earlier.


At the same time, you can ensure that receiving messages from the server occurs not only as a reaction to some requests from us. The actions of other users can cause them. To test this, you can establish a connection in another tab using another user's authentication token. A message from the server notifying this will be sent to all tabs with an active connection.

Business process for messaging

Now you can continue to develop the capabilities of the WebSocket and create a business process for messaging. By the way, you can send messages now, but without first creating the logic, this makes no sense, the message will not lead to any reaction. Therefore, let's go back to the endpoint settings and create a business process for the receive trigger.

In many ways, it will be similar to the previous business process. When a message is received, it will be necessary to generate a chat_event and send notifications about it to all chat participants. The difference is that the message itself will need to be added to the chat_event, and the author of the message does not need to be included in the mailing list.

The same blocks are used in the first part of the business process. In the Make chat_event block, you need to set type = message and attach the message itself from the start block.


In the loop, we need to check (Equal block) and send the message only if the connection ID of the receiver does not match the connection ID of the sender (If-Else = False).


You can publish the result and start testing. Note that the message itself is in JSON format, so when using the message variable, it will look this way:

{"message":"Some text here"}

In the example, you can see that you receive a chat connection notification, send your own message (Hi!), and receive a response (Glad to see you!)


This completes the creation of the basic backend for chat using WebSockets. You can start building the front-end and develop your own real-time messaging app.

Was this article helpful?

AppMaster.io 101 Crash Course

10 modules
2 weeks

Not sure where to start? Get going with our crash course for beginners and explore AppMaster from A to Z.

Start Course
Development it’s so easy with AppMaster!

Need More Help?

Solve any issue with the help of our experts. Save time and focus on building your applications.

headphones

Contact Support

Tell us about your problem, and we’ll find you a solution.

message

Community Chat

Discuss questions with other users in our chat.

Join Community