0
// Client.js file

const socket = io('http://localhost:8000');

const form = document.getElementById("send-con");
const msginput = document.getElementById("msginp");
const msgcontainer = document.querySelector(".container");
const username = prompt("Enter Your Name to Join");
socket.emit('new-user-joined', username);
// Index.html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iChat - Realtime Node Socket.io Chat App</title>
    <script src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script src="js/client.js"></script>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>

    <nav>
        <img class="logo" src="chat.jpg" alt="">
    </nav>

    <div class="container">
        <div class="message right">Hey Maan ! How are you ?</div>
        <div class="message left">I am fine! What about you dear ?</div>
    </div>

    <div class="send">
        <form action="#" id="send-con">
            <input type="text" name="msginp" id="msginp">
            <button class="btn" type="submit">Send</button>
        </form>
    </div>

</body>

</html>
// index.js file

// Node server which will handle Socket io connections
const express = require('express');
const app = express();
const server = require('http').createServer(app);

// 'socket.io' server is running on port 8000. It is used to listen incoming events.

const io = require('socket.io')(8000, {
    transports: ['websocket']
});

const cors = require('cors');

app.use(cors());

// Users will be updated when someone joined the chat.
const users = {};

// io.on listen events when a connection is established & socket.on will listen a particular event
io.on('connection', socket => {
    socket.on('new-user-joined', username => {
        // console.log(`New user ${users[socket.id]} Joined the chat`);
        console.log("New user ", username, "Joined the chat");
        users[socket.id] = username;
        socket.broadcast.emit('user-joined', username);
    });

    socket.on('send', message => {
    socket.broadcast.emit('receive', { message: message, username: user[socket.id] });

    socket.on('disconnect', () => {
        console.log(username, 'disconnected');
    socket.broadcast.emit('user-disconnected', user[socket.id]);
    delete users[socket.id];
    });
    });
});

I have connected the index.js (server side) file with the client.js (client-side) file using const socket = io('http://localhost:8000'); and emitting "const username = prompt("Enter Your Name to Join"); socket.emit('new-user-joined', username);" but it's not working. I want to listen an event whenever a new user joined the chat. It should be written in the terminal but it's not displaying anything.

This callback should be fired

io.on('connection', socket => {
socket.on('new-user-joined', username => {
    // console.log(`New user ${users[socket.id]} Joined the chat`);
    console.log("New user ", username, "Joined the chat");
    users[socket.id] = username;
    socket.broadcast.emit('user-joined', username);
});

and display a name of the new user in the terminal.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I think you might need to wait for the socket.io to connect. What happens if you create a button instead that calls `socket.emit`? – Tae Hyung Kim Feb 25 '23 at 21:17
  • If that is the case, try wrapping your code in username prompt and socket.emit in `socket.on('connect', () => {})`. – Tae Hyung Kim Feb 25 '23 at 21:19
  • can you put a console.log statement after io.on('connection') and check if client side is able to make connection or not? – Munam Tariq Mar 19 '23 at 21:06

0 Answers0