Socket using NodeJS
Excited to dive into the world of sockets! 🌐
Hey LinkedIn fam! 👋 As a beginner exploring the fascinating realm of networking, I've been getting my hands dirty with sockets lately.
What is a Socket in JavaScript?
Imagine a Socket as a digital telephone line that allows real-time communication between a server and a client. It's like a continuous connection that enables data to flow back and forth instantly.
⚡️ Why Sockets? ⚡️
Sockets are game-changers for web applications requiring instant updates or real-time interaction. They facilitate dynamic content updates, live chat, multiplayer gaming, and live-streaming by maintaining a constant channel between the server and clients.
Use of Sockets:
Real-time Updates: Sockets ensure that any changes on the server are immediately reflected on the client-side without manual refreshing.
Instant Messaging: Enable live chat applications where messages appear instantly.
Collaborative Environments: Power collaborative tools allowing multiple users to work simultaneously on shared content.
// Initialization - Setting up a Socket Connection
const { Server } = require("socket.io"); // Import the socket.io Server class
// Creating an HTTP server
const httpServer = require("http").createServer();
// Creating a Socket.IO instance and attaching it to the HTTP server
const io = new Server(httpServer, {
cors: {
origin: "*"
},
});
// This function triggers once the connection is established, confirming successful connectivity.
io.on("connection", async (socket) => {
console.log("*** Connected Socket & User ***", {
socketId: socket?.id,
});
// Send data through the socket
socket.emit('message', 'Hello, client!');
// Transmitting data to the connected client through the socket connection.
// Receive data through the socket
socket.on('message', (data) => {
console.log('Received message from client:', data);
});
// Listening for incoming messages from the client and displaying them in the console.
// Disconnect handling
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
// Define the port for the server to listen on
const PORT = process.env.PORT || 3000;
// Start the server
httpServer.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This code initializes a Socket connection, sends a message to the server, and listens for messages from the server. It's like dialing a number, speaking, and hearing responses in real-time over a digital line.
Sockets revolutionize web applications by enabling lightning-fast, real-time communication, offering a gateway to dynamic and interactive user experiences!
Full Stack Shopify developer | Expert in ChatGPT, Open API Integration, and Plugin Development | I helped publish 10+ Shopify App Store apps and provided 300+ private solutions
1ySalaam Haris, we're hiring MERN stack expert. please share your latest resume if you interested.