In this post we will be discussing about creating WebSocket client in Node.js. For creating a WebSocket client we will be using ws module which will allow us to create a WebSocket client outside of the browser environment. Please read How to create WebSocket Server in Node.js before creating WebSocket Client.
Creating WebSocket Client
var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8075");
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(message) {
message = message.trim();
ws.send(message, console.log.bind(null, 'Sent : ', message));
});
ws.on('message', function(message) {
console.log('Received: ' + message);
});
ws.on('close', function(code) {
console.log('Disconnected: ' + code);
});
ws.on('error', function(error) {
console.log('Error: ' + error.code);
});
In the above code we are first creating the WebSocket with the URL (ws://localhost:8075). Now we are getting the input from the user using stdin(). So anything entered into the STDIN of the client will be sent to the server. Now we have three events (message, close and error) on WebSocket to know about the status of the communication between the server and client.
In the below video you will see that in one of the Node.js terminal we have started WebSocket Server and in other terminal we have started WebSocket Client. So from client we send the message to the server and it is received in the server. When we disconnect the server, it is being shown on the client with the code.
Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.
Creating WebSocket Client
var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8075");
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(message) {
message = message.trim();
ws.send(message, console.log.bind(null, 'Sent : ', message));
});
ws.on('message', function(message) {
console.log('Received: ' + message);
});
ws.on('close', function(code) {
console.log('Disconnected: ' + code);
});
ws.on('error', function(error) {
console.log('Error: ' + error.code);
});
In the above code we are first creating the WebSocket with the URL (ws://localhost:8075). Now we are getting the input from the user using stdin(). So anything entered into the STDIN of the client will be sent to the server. Now we have three events (message, close and error) on WebSocket to know about the status of the communication between the server and client.
In the below video you will see that in one of the Node.js terminal we have started WebSocket Server and in other terminal we have started WebSocket Client. So from client we send the message to the server and it is received in the server. When we disconnect the server, it is being shown on the client with the code.
Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.
No comments:
Post a Comment