Introduction - potatoscript/websocket GitHub Wiki
WebSocket is a special communication system that lets computers talk to each other instantly without waiting!
๐ก Imagine:
- HTTP (old way) ๐จ โ Like sending a letter to a friend and waiting for a reply.
- WebSocket (new way) ๐ โ Like talking on the phone โ instant messages!
โ
Fast โ Messages are sent in real-time (no delays!)
โ
Lightweight โ Uses fewer resources than HTTP
โ
Two-way Communication โ The server and the client can send messages anytime!
โ
Great for Real-time Apps โ Chat apps, multiplayer games, stock price updates
๐ Let's create a simple WebSocket server using Node.js!
๐น First, make sure you have Node.js installed.
๐น Download it from here and install it.
To check if it's installed, open your terminal (Command Prompt or Terminal) and type:
node -v
If it shows a version number, you're ready! โ
Now, letโs create a folder for our WebSocket project:
mkdir websocket-demo
cd websocket-demo
Inside this folder, initialize a Node.js project:
npm init -y
This will create a file called package.json (it keeps track of our project settings).
We need a special tool to create WebSockets in Node.js. Letโs install it:
npm install ws
๐ Now, let's create our WebSocket server!
1๏ธโฃ Inside your websocket-demo
folder, create a new file called server.js.
2๏ธโฃ Open it and add this code:
// 1๏ธโฃ Import the WebSocket library
const WebSocket = require('ws');
// 2๏ธโฃ Create a WebSocket Server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
console.log("๐ก WebSocket Server is running on ws://localhost:8080");
// 3๏ธโฃ Handle new connections
wss.on('connection', (ws) => {
console.log("โ
A new client connected!");
// 4๏ธโฃ Send a welcome message to the client
ws.send("๐ Welcome to the WebSocket Server!");
// 5๏ธโฃ Listen for messages from the client
ws.on('message', (message) => {
console.log(`๐ฉ Received: ${message}`);
// 6๏ธโฃ Send back a reply
ws.send(`๐ Server says: You said "${message}"`);
});
// 7๏ธโฃ Handle client disconnection
ws.on('close', () => {
console.log("โ A client disconnected");
});
});
๐ Explanation:
โ We create a WebSocket server on port 8080.
โ When a client connects, we send a welcome message.
โ When the client sends a message, the server replies.
โ If the client disconnects, we log it.
โ Now, run the WebSocket server in the terminal:
node server.js
๐ Your WebSocket server is now running!
๐ Letโs connect to our WebSocket server using a web page!
1๏ธโฃ Create a new file called index.html inside your websocket-demo
folder.
2๏ธโฃ Open it and 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 Demo</title>
</head>
<body>
<h1>๐ก WebSocket Client</h1>
<p>Status: <span id="status">๐ด Disconnected</span></p>
<input type="text" id="messageInput" placeholder="Type a message..." />
<button onclick="sendMessage()">๐ Send</button>
<ul id="messages"></ul>
<script>
// 1๏ธโฃ Connect to WebSocket Server
const socket = new WebSocket("ws://localhost:8080");
// 2๏ธโฃ Update status when connected
socket.onopen = () => {
document.getElementById("status").textContent = "๐ข Connected";
};
// 3๏ธโฃ Receive messages from the server
socket.onmessage = (event) => {
const messageList = document.getElementById("messages");
const newMessage = document.createElement("li");
newMessage.textContent = `๐ฉ ${event.data}`;
messageList.appendChild(newMessage);
};
// 4๏ธโฃ Send a message to the server
function sendMessage() {
const input = document.getElementById("messageInput");
const message = input.value;
socket.send(message);
input.value = "";
}
// 5๏ธโฃ Handle disconnection
socket.onclose = () => {
document.getElementById("status").textContent = "๐ด Disconnected";
};
</script>
</body>
</html>
โ
Now, open index.html
in a browser and test your WebSocket!
- Type a message and click "Send" โ The server will reply instantly!
- If the server is stopped, the status will turn red ๐ด.
1๏ธโฃ Start the WebSocket server:
node server.js
2๏ธโฃ Open index.html
in a browser.
3๏ธโฃ Send messages! ๐
โ Real-time Chat Apps ๐ฌ
โ Multiplayer Games ๐ฎ
โ Live Stock Market Updates ๐
โ IoT Device Communication ๐ค
Congratulations! ๐ You have learned:
โ
What WebSocket is ๐ก
โ
How to create a WebSocket server โก
โ
How to connect from a browser ๐
โ
How to send & receive messages โ