Socket.io event doesn't emitting from client itself client

20 views Asked by At

I am making a simple chat app website in Socket.io. But emit method not working in client. when i do on and emitting event from client it doesn't do on function here is client html body code :

<body>
  <ul id="messages"></ul>
  <form id="form" action="">
    <input id="input" autocomplete="off" /><button>Send</button>
  </form>

  <script src="/socket.io/socket.io.min.js"></script>
  <script>
    const socket = io();

    socket.on("chat", (msg) => {
      console.log(msg);
    });

    socket.emit('chat', 'hello');
  </script>
</body>

and this server file content:

const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const { Server } = require("socket.io");

const app = express();
const server = createServer(app);
const io = new Server(server);

app.get("/", (req, res) => {
  res.sendFile(join(__dirname, "index.html"));
});

io.on("connection", (socket) => {
  console.log("a user connected");
});

server.listen(4001, () => {
  console.log("server running at http://localhost:4001");
});

0

There are 0 answers