Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Socket not emit messages

I’ve had a problem with receiving message from client to server with using React and ExpressJS. After launch sendMessage function on client side I want to send to server my message, but, I don’t know why this message is not being received by my server and io.on("message", (message) => { is not launched with his console.log :/

Here is my code

Server side:
index.ts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const server = http.createServer(app);
export const socketIo = socket(server);

socket.ts

export const socket = (httpServer: any) => {
    const io = new Server(httpServer, { cors: { origin: "http://localhost:5000" } });

    io.on("connection", (socket) => {
        console.log("Socket connected!")
        socket.emit('connection', null);
    });

    io.on("message", (message) => {
        console.log("NEW MESSAGE: ", message)
    })
}

Client side:
App.tsx

const SOCKET_SERVER = "http://127.0.0.1:3000";

export const socket = socketClient(SOCKET_SERVER);
socket.on('connect', () => {
  console.log('CONNECTED WITH BACKEND SOCKET')
})

Chat.tsx

  const sendMessage = () => {
    const message = form.getFieldsValue()["typedMessage"];

    socket.emit("message", message);
    
    form.resetFields();
  };

thanks for any help!

>Solution :

io.on("connection", (socket) => {
    console.log("Socket connected!")
    socket.emit('connection', null);
});

io.on("message", (message) => {
    console.log("NEW MESSAGE: ", message)
})

The "connection" is triggered on the server listener and provides a connected socket. The socket is then used to receive messages. This means receiving messages must be done on socket, not on the listener io:

io.on("connection", (socket) => {
    console.log("Socket connected!")
    socket.emit('connection', null);

    socket.on("message", (message) => {
        console.log("NEW MESSAGE: ", message)
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading