starting template for socket.io server in node in javascript

You can use the following code as a starting template for creating a Socket.IO server with Node.js:

index.tsx
// Import required modules
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

// Create a new express app
const app = express();
// Create a new http server using the express app
const server = http.createServer(app);
// Create a new socket.io server using the http server
const io = socketIo(server);

// Listen for incoming socket.io connections
io.on('connection', (socket) => {
    console.log(`New client connected with ID ${socket.id}`);

    // Listen for a "chat message" event from the client
    socket.on('chat message', (msg) => {
        console.log(`Message received from client with ID ${socket.id}: ${msg}`);

        // Broadcast the message to all connected clients except the sender
        socket.broadcast.emit('chat message', msg);
    });

    // Listen for the "disconnect" event, i.e. a client has disconnected
    socket.on('disconnect', () => {
        console.log(`Client with ID ${socket.id} has disconnected`);
    });
});

// Start the server listening on the specified port
const port = 3000;
server.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});
1165 chars
36 lines

This code creates an express app and an http server using the createServer method provided by Node's built-in http module. It also creates a socket.io server using the http server.

The io.on('connection') method listens for incoming socket.io connections from clients. When a client connects, a new socket object is created to represent the connection. This socket object can be used to communicate with the client.

The code also listens for a chat message event from the client using the socket.on('chat message') method. When a message is received from a client, it is logged to the console, and then broadcasted to all connected clients except the sender using the socket.broadcast.emit() method.

Finally, the code listens for the disconnect event using the socket.on('disconnect') method, which is triggered when a client disconnects from the server.

gistlibby LogSnag