Android chat app with WSS (WebSocket Secure) connection. MVP architectural pattern has been used.
Run the server.js file including the code block:
// 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 => {
const obj = JSON.parse(data);
console.log(`Client -${obj.clientName}- has sent us: ${obj.message}`)
});
// handling what to do when clients disconnects from server
ws.on("close", () => {
console.log("the client has disconnected");
});
// handling client connection error
ws.onerror = function () {
console.log("Some Error occurred")
}
});
console.log("The WebSocket server is running on port 8080");
Run the client.html file including the code block:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>NodeJS WebSocket Client</title>
</head>
<body>
<h1>Hello world</h1>
<script>
const ws = new WebSocket("ws:https://localhost:8080");
ws.addEventListener("open", () =>{
console.log("We are connected");
const data = JSON.stringify({ clientName: 'web client', message: 'How are you?' })
ws.send(data);
});
ws.addEventListener('message', function (event) {
console.log(event.data);
});
</script>
</body>