ok, for communicating with server we need a Websocket Server - i prefer we develop our WebSocket server-side with nodejs.
our source code => Github Link
What is WebSocket?
Websocket is a simple to use, fast and tested WebSocket client and server implementation.
The Websocket specification defines an API establishing a connection between a web browser and server. WebSocket is used for creating real-time games, chat applications, displaying stock data, etc.
NodeJS and WebSocket
NodeJS is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It is easy to build a WebSocket server implementation with NodeJS.
Traditional HTTP is dependent on client requests, you have to send your request to the server and then get a response from it but in WebSocket, you can send data to the client from the server directly which we call bidirectionally.
Let me introduce you to Websockets: An event-driven, web-friendly alternative to HTTP. Websockets don't require a client request to fetch data from the server every time.
Building a WebSocket Server With NodeJS
As prerequisites, you should have Nodejs and NPM Installed in your system. If you don’t have it, download and install it from here: https://nodejs.org/en/download/
1) Once you are ready with NodeJs, open a terminal and type the following commands:
mkdir webSocketServer && cd webSocketServer
2) Create your nodejs project environment:
npm init -y
3) Next, run the following command to install the ws library as a dependency:
npm install ws
4) Create a javascript file for example “webSocketServer.js” and paste the following code for creating a web server:
// Importing the required modules
const WebSocketServer = require('ws');
// Creating a new websocket server
const wss = new WebSocketServer.Server({ port: 8080 })
// Creating connection using websocket
wss.on("connection", ws => {
console.log("new client connected");
// sending message
ws.on("message", data => {
console.log(`Client has sent us: ${data}`)
});
// handling what to do when clients disconnects from server
ws.on("close", () => {
console.log("the client has connected");
});
// handling client connection error
ws.onerror = function () {
console.log("Some Error occurred")
}
});
console.log("The WebSocket server is running on port 8080");
This code will create a basic WebSocket Server for you and you can provide any port you want while creating the WebSocket server.
5) For testing it, open up a terminal and type:
node webSocketServer.js
Reference:
1) piesocket.com
In part 5 we are going to write our WebSocket client-side service with Golang WebAssembly and connect to WebSocket nodejs server-side😉
Top comments (0)