Real-Time Implementation Of Golang,WebSocket and Angular 2

 In Technologies
0
343 Views

As we know Golang is a powerful programming language introduced by Google and we can use this to implement the real-time applications. So, here we are going to use this to implement a Real-Time Chat Application, with the help of Golang, WebSocket and Angular 2. This implementation consist of two different implementations first is Chat Server and another one is Chat Client.

So, let’s move forward…

Introduction of Golang, WebSocket and Angular 2

Basics lay the strong foundation of anything so, it’s important to know about the basics…

WebSocket

It is a computer communication protocol that provides full-duplex (a point-to-point communication system that allows communication in both directions simultaneously) communication channels over a single TCP connection. It is a different TCP protocol from HTTP both protocols take place at layer 7 in the OSI model and depend on TCP at layer 4.

This is a protocol that allows interaction between a browser and a web server with lower overheads and facilitating real-time data transfer from browser to the server. So in this way, two-way (bi-directional) conversation can take place between a browser and the server.

webSocket img

Angular 2

It is a Typescript (free and open-source programming language) open-source front-end web application platform (Software Framework, that supports the development of web applications including web services, web resources and web APIs). It exceeds the capabilities of other competing frameworks.

Angular 2 is totally different from Angular 1, but it is based on the idea that originally made Angular 1 great, as well as some new ideas and technologies. It is a revised version of Angular 1 that replaced the complicated code of Angular 1.

Some Features of Angular 2 are as follows…

  • Components
  • TypeScript
  • Services

It contains components like…

  • Modules  (Designed to perform a single task).
  • Component  (Used to bring the modules together).
  • Metadata  (It is to add more data to an Angular 2 class).
  • Services  (Create components, shared across the entire application).
  • Templates  (Used to define the views of an Angular 2 application).

 

So, after the introduction part let’s come to the requirements and the process of the real-time implementation of the application. Here, we are going to develop a chat application using mention technologies.

Requirements To Develop a Chat Application

This application contains many pieces so that we have few requirements that must be met in order to be successful.

The requirements are as follows:

  • Golang 1.7+
  • js 4.0+
  • The Angular 2 CLI

The client front-end will be written in Angular 2 that has a dependency of the NPM (Node Package Manager, makes to share and reuse code and it makes it easy to update the code that you are sharing) which ships with Node.js. The clients will be written in the Go programming language and chat server that will adopt all the messages.

Implementation Of Golang Chat Server

Let’s start with the server component of an application which has some external dependencies that must be downloaded first. So firstly execute the following code from the Command Prompt ( Windows ) or Terminal ( Mac and Linux ).

Golang

We need a UUID (universally unique identifier) library so we can assign each chat client a unique id value.

Now, create a new project at $GOPATH that will represent chat server. The project will be found in the $GOPATH/src/github.com/nraboy/realtime-chat/main.go file.

The application will have three types of data structure:

Here, I want to tell you something that I have been taken these examples from other sources like Gorilla WebSocket chat example and some other blogs.

Let’s go ahead…

The ClientManager structure will keep connected all the clients who are trying to register, clients that have become destroyed, and those who are waiting to be removed. ClientManager structure also takes care of the messages that are to be broadcast from the all connected clients.

For sending a message, a client has a unique id, a socket connection, and a message.

Instead of passing a string of data that cannot easily be tracked, we are passing JSON data, to add complexity to the data being passed. Each message will contain the information regarding the sender of the message, receiver of the message, and the actual content of the message.

Here, the server will use three goroutines, one for managing the clients, one for reading WebSocket data, and one for writing WebSocket data. Goroutines will run in a loop until they are no longer needed.

Let’s start with the Server  Goroutine…

If a channel called  “manager.register” has data then a mapping takes place between the clients, managed by the ClientManager. After mapping the clients, a JSON message sent to all other clients but not including the one that connected immediately.

When a client disconnects for any reason, the channel called “manager.unregister” will have data. The channel data in the disconnected client will be closed and the client will be removed from the client manager.

If the channel called “manager.broadcast” has data it means that we are trying to send messages and receive messages. We need to loop each managed client sending the message to each of them. If any reason message cannot be sent that time we assume, that the client has disconnected and we remove them.

The “manager.send” method created a loop through each of the clients to save repetitive code :

 

Now, come to the Goroutine for reading WebSocket data sent from the clients. This goroutine read the socket data and add it to the “manager.broadcast” for further use.

If any error occurs in reading the WebSocket data it means the client has disconnected by the ClientManager. So, in this case, we need to unregister the client from the server.

The “con.send” channel handled in the third goroutine for writing data. If  “c.send” has data, we try to send the message. If any reason, the channel is not alright then we will send a disconnect message request to the client. When we start our server, a server-side goroutine started. The other goroutines will start when someone connects to the server.

So in this way, have a look at the main function:

The server starts on port 12345 and it has a single endpoint and only accessible via a WebSocket connection. This endpoint method called wsPage and it looks like :

When we need to upgrade an HTTP request to the WebSocket request that time we used WebSocket library. When there is any request from outside domains, we can accept these requests by adding CheckOrigin that eliminates cross-origin resource sharing (CORS) errors.

When a connection is established, the client is created & a unique id generated for that client and the read & write goroutines are triggered.

Application run with the following :

                     go run *.go

Conclusion

So, this blog is all about the implementation of  Chat Server using Golang. But all we know that we have to need a Chat Client also to implement a successful Chat Application.

We’ll discuss the Chat Client in my next blog… 🙂

Recommended Posts

Start typing and press Enter to search