Typetron now has WebSockets
Tags: typetron, typescript, node, websocket
Published: 2021-12-03 20:16:52

### Intro

[Typetron](https://typetron.org/) aims to have one of the easiest and most intuitive developer experiences in a framework. That's why all of the Typetron's features merge seamlessly between each other offering your app a sense of belonging when you combine your business logic with the framework.

### What's new
The last addition to the Typetron's toolbelt is the ability to create real-time, interactive applications using [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) in easy and simple way.

_TLDR: Here is a [repo](https://github.com/typetron/websockets-examples) with WebSockets examples using Typetron and different technologies: Angular, React, Vue or just a simple Webpack setup._


### Configuring WebSockets
Typetron comes with the WebSocket server activated by default on port `8001`. This setting is in the `app/config.ts` file:

```ts
import { AppConfig } from '@Typetron/Framework'
export default new AppConfig({
    // ...
    websocketsPort: 8001,
    // ...
})
```
_If you want to remove the WebSocket feature from you app, just remove the port `websocketsPort` config line._

Once you [start](https://typetron.org/docs/installation) your Typetron app you will see a message in the command line saying that your WebSocket server started on that port:
```
Websocket server started on port 8001
```

### Creating WebSockets events on the backend side
Now, you can start receiving and sending WebSocket messages from and to the server. All we have to do is to define what events our app will handle. You can [add an event](https://typetron.org/docs/websockets/controllers-and-events) in any of your controllers by creating a method that has the `@Event()` decorator. Take a look at this example:

```ts
import { Controller, Event } from '@Typetron/Router'

@Controller()
export class MainController {

    @Event()
    welcome() {
        return 'Welcome to Websockets'
    }
}
```

### Listening to WebSockets events - solution 1
Having this, we can now create a client that will send and receive WebSocket events. Typetron comes with a handy frontend package that will help you do just that. You can install it in your app (Angular, React, Vue, etc.) using this command:

```bash
$ npm install @typetron/websockets
```

After installing it, we can connect to our server and start sending and receiving events. Let's fire the `welcome` event and listen for a response back from the server:
```ts
import { Websocket } from '@typetron/websockets'

export const socket = new Websocket('ws://localhost:8001')

socket.on('welcome').subscribe(response => {
    console.log('Backend response', response)
})

socket.emit('welcome')

```

You should now see this message in the console:
```
Backend response Welcome to Websockets
```

### Listening to WebSockets events - solution 2
If you don't want to use `@typetron/websocket` library in your frontend app, you can easily just connect to the WebSocket server using the built-in WebSocket API from Javascript but doing so, you will have to manually parse the Typetron WebSocket message on your frontend app. The format of the message is a simple JSON object that looks as follows:
```json
// when sending a message
{
    "event": "event name",
    "message": { // optional
        "body": "content sent to the controllers",
        "parameters": ["param1","param1"] // controller method parameters (optional)
    }
}

// when receiving a message
{
    "event": "event name",
    "status": "OK" // or "Error",
    "message": "backend response" // optional
}
```

Having this in mind, let's connect to Typetron using the Javascript's built-in WebSocket API:

```ts
const socket = new WebSocket('ws://localhost:8001')

socket.onopen = () => {

    socket.onmessage = message => {
        const response = JSON.parse(message.data)
        console.log('Backend response', response.message )
    }

    socket.send(JSON.stringify({event: 'welcome'}))
}
```

Opening your frontend up should result in a console message similar to the one above:
```
Backend response Welcome to Websockets
```

### Outro
And that's it. You can now build real-time apps using Typetron and WebSockets. Keep in mind that this feature is still in progress as many more functionalities will added.

Here is a [repo](https://github.com/typetron/websockets-examples) with WebSockets examples using Typetron and different technologies: Angular, React, Vue or just a simple Webpack setup.

In the next articles in this "Typetron WebSockets" series we will build a "ToDo app" with Angular, React and Vue. [Subscribe](https://typetron.org/) to the newsletter to be notified when we publish these articles.


Check the website [typetron.org](https://typetron.org)
Github [repo](https://github.com/typetron)
Let's talk on [Discord](https://discord.gg/t6jffd4Q)
Typetron Twitter [@Typetron_](https://twitter.com/Typetron_)
My twitter [@ionellupu_](https://twitter.com/ionelLupu_)
Come and leave a question on [Reddit](https://www.reddit.com/r/typetron)
Join [the Facebook](https://www.facebook.com/Typetron-662589810876633/) group