Connection - potatoscript/websocket GitHub Wiki
A WebSocket connection is like a magic telephone βοΈ that lets the client (browser) and server talk to each other instantly! Unlike normal web pages that keep asking for new messages, WebSockets allow us to send and receive messages instantly in real time.
π‘ Why do we need a server?
The server is like a radio station π‘βit sends and receives messages from clients (browsers).
1οΈβ£ Open your project folder websocket-demo.
2οΈβ£ Create a new file called server.js.
3οΈβ£ Open the file in VS Code or any code editor.
Inside server.js, add the following code:
// π οΈ Import the WebSocket library
const WebSocket = require("ws");
// π‘ Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
console.log("β
WebSocket server is running on ws://localhost:8080");
// π Listen for client connections
wss.on("connection", (ws) => {
console.log("π A client has connected!");
// π© Listen for messages from the client
ws.on("message", (message) => {
console.log("π¨ Received:", message.toString());
// π Send a reply back to the client
ws.send("π Server says: Message received!");
});
// β Handle client disconnections
ws.on("close", () => {
console.log("πͺ A client has disconnected.");
});
});
β
Import the WebSocket library to use WebSockets.
π‘ Create a WebSocket server that listens on port 8080
.
π Detect when a client connects and send/receive messages.
π¨ Print received messages and send a response.
πͺ Handle disconnections when a client leaves.
π‘ Now, letβs start our server!
1οΈβ£ Open your terminal or command prompt.
2οΈβ£ Make sure you're inside the websocket-demo folder.
3οΈβ£ Run this command:
node server.js
4οΈβ£ You should see:
β
WebSocket server is running on ws://localhost:8080
π Congratulations! Your WebSocket server is now running! π
π‘ Now we need a "listener" (client) to connect to our server!
1οΈβ£ Create a new file called client.html inside your websocket-demo folder.
2οΈβ£ Open the file in VS Code or any text editor.
Inside client.html, add this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client π</title>
</head>
<body>
<h2>π‘ WebSocket Client</h2>
<button onclick="sendMessage()">π© Send Message</button>
<p id="status">π΄ Disconnected</p>
<p id="messages"></p>
<script>
// π Create a WebSocket connection to the server
const socket = new WebSocket("ws://localhost:8080");
// π Connection opened
socket.onopen = function () {
document.getElementById("status").textContent = "π’ Connected to Server!";
console.log("β
Connected to WebSocket server");
};
// π© Handle incoming messages
socket.onmessage = function (event) {
console.log("π¨ Server:", event.data);
document.getElementById("messages").innerHTML += "<p>π¨ " + event.data + "</p>";
};
// πͺ Handle connection close
socket.onclose = function () {
document.getElementById("status").textContent = "π΄ Disconnected";
console.log("β Disconnected from WebSocket server");
};
// π€ Send a message to the server
function sendMessage() {
socket.send("Hello Server! π");
console.log("π© Sent: Hello Server! π");
}
</script>
</body>
</html>
π’ Creates a WebSocket connection to the server.
π© Sends a message when the button is clicked.
π¨ Receives messages from the server and displays them.
π΄ Handles disconnections when the server stops.
1οΈβ£ Start the WebSocket server:
node server.js
β You should see:
β
WebSocket server is running on ws://localhost:8080
2οΈβ£ Open the client (HTML page):
- Open client.html in a web browser (Chrome, Edge, Firefox).
- You should see "WebSocket Client" and a π© Send Message button.
3οΈβ£ Click the "π© Send Message" button:
- The server will print:
π¨ Received: Hello Server! π
- The client will display:
π Server says: Message received!
-
Connect to your webSocket
const ws = new WebSocket('ws://127.0.0.1:9876')
-
Send message
ws.send("some message here")
-
Access connection from the front end to the back end
- install nodemon
npm i -g nodemon
- next run
nodemon index.js
- after install the nodemon and run it you can receive the message with
const WebSocket = require('ws') const wss = new WebSocket.Server({ port: 9876 }) wss.on('connection', function(ws){ ws.send("Hello from the server") })
- install nodemon
-
to get the message data of client from the server
ws.on('message',function(data){
console.log(data)
})
- to get the message data of server from the client
ws.onmessage=function(data, isBinary){
const message = isBinary ? data : data.toString();
console.log(message)
}
- resend back the message of client from the server
ws.on('message',function message(data, isBinary){
const message = isBinary ? data : data.toString();
ws.send(message)
})
- To make a connection from client side
const url = 'ws://localhost:9876/websocket'
const server = new WebSocket(url)
server.onopen = function(){
server.send("Hi")
server.send("this is lim")
}
- add multiple client in the server
wss.on('connection', function(ws){
//ws.send("Hello from the server")
ws.on('message',function message(data, isBinary){
const message = isBinary ? data : data.toString();
//ws.send(message)
wss.clients.forEach(function each(client){
if(client.readyState === WebSocket.OPEN){
client.send(message)
}
})
})
})
- webSocket readyState