简体   繁体   中英

socket.emit and socket.on is not connected

I was adding a chat page in my existing express app using socket.io. My server code :

var io = socket(server);
io.on('connection', (socket) => {
    console.log('made socket connection', socket.id);
    // Handle chat event
    socket.on('chat', function(data){
        console.log("second");
        io.sockets.emit('chat', data);
    });

});

and my client code :

var socket = io.connect("http://localhost:3000/chat")

//Query elements
var message = document.getElementById('message'),
    btn     = document.getElementById('send'),
    output  = document.getElementById('output');

btn.addEventListener("click", function(){
    socket.emit('chat', {
        message: message.value,
    });
    console.log("First")
    message.value = "";
})     
socket.on('chat', function(data){
    console.log("final function")
    output.innerHTML += `<p>${data.message}</p>`;
});

socket.emit is fired on click in client side but socket.on in server doesn,t run. Note : console.log('made socket connection', socket.id); run normally

there is an issue in your client side . you are trying to connecting with namsespaces "chat" , remove chat

var socket = io.connect("http://localhost:3000")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM