Friday, March 5, 2021

How to Create WebSocket Server & Client using Node.JS and JavaScript


You can follow the syntax below to create Websocket Server using Node.JS and WebSocket Client using JavaScript.

websocker-server.js

/*
	NodeJS WebSocket Server Example
	--------------------------------------------------

	Step 1 : $ npm install websocket
	Step 2 : Write Code
	Step 3 : Run
		 $ node websocket-server.js
	Step 4 : Done

	--------------------------------------------------
	Reference :
		- https://www.npmjs.com/package/websocket
		- https://www.pubnub.com/blog/nodejs-websocket-programming-examples/
*/

const http = require('http');
const WebSocketServer = require('websocket').server;
const server = http.createServer();

server.listen(9898, () => {
	console.log('WebSocket Server at localhost:9898')
});

const wsServer = new WebSocketServer({
	httpServer: server
});

wsServer.on('request', function(request) {
	const connection = request.accept(null, request.origin);

	console.log('\n\n>> REQUEST : ');
	console.log(request);

	console.log('\n\n>> PATHNAME : ');
	console.log(request.resourceURL.pathname);

	console.log('\n\n>> WSSERVER OBJECT : ');
	console.log(wsServer);

	console.log('\n\n>> CONNECTION STATE : ');
	console.log(connection.state);

	console.log("\n\n>> QUERY STRING : ");
	console.log(request.resourceURL.query);

	console.log("\n\n>> GET PARAMETER['q'] : ");
	console.log(request.resourceURL.query.q);

	console.log('\n\n>> CONNECTION : ');
	console.log(connection);

	connection.on('message', function(message) {
		console.log('Received Message :', message.utf8Data);
		connection.sendUTF('Hi this is WebSocket server!');
		connection.close();
	});
	
	connection.on('close', function(reasonCode, description) {
		console.log('Client has disconnected - Reason Code : ' + reasonCode + ' - Description : ' + description);
	});
});


websocket-client.html

<!--
	JavaScript WebSocket Client
	---------------------------------------------

	Reference :
		- https://www.pubnub.com/blog/nodejs-websocket-programming-examples/
		- https://www.npmjs.com/package/websocket
-->

<!DOCTYPE html>
<html>
<head>
	<title>WebSocket Playground</title>
</head>
<body>
</body>
</html>

<script type="text/javascript">

const ws = new WebSocket('ws://localhost:9898/farizfadian?q=abc');

ws.onopen = function() {
	console.log('WebSocket Client Connected');
	ws.send('Hi this is web client.');
};

ws.onmessage = function(e) {
	console.log("Received : '" + e.data + "'");
};

ws.onclose = function() {
	console.log('Disconnected');
};

</script>


Reference :


Previous Post
Next Post

0 komentar: