简体   繁体   中英

socket io not receiving events for both client and server

I followed the socket io website and implement client and server, below is my code

server

const exp = require('express')();
const http = require('http').createServer(exp);
const io = require('socket.io')(http,{
    cors : {
        origin : '*'
    }
});

http.listen(3000, () => {
    console.log('listening on *:3000');
    setInterval(function(){
        io.sockets.emit('hi', 'everyone');
    },1000);

    io.sockets.on('connection', function (socket) {
        socket.on('hello', function (msg) {
            console.log(msg);
        });
    });
});

client

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.4.0/socket.io.js" integrity="sha512-Y8KodDCDqst1e8z0EGKiqEQq3T8NszmgW2HvsC6+tlNw7kxYxHTLl5Iw/gqZj/6qhZdBt+jYyOsybgSAiB9OOA==" crossorigin="anonymous"></script>
<script>
  let socket = io('http://localhost:3000',{
     transports : ['websocket']
  });

  socket.on('hi', function(msg) {
    console.log(msg);
  });

  socket.emit('hello','Hello server, im client');

  socket.on('connect', function() {
    console.log(socket.connected); // true
  });
</script>

neither event hi nor hello arrived nor received from and to both client and server, no error whatsoever when running the script and client connecting to server. Any help is greatly appreciated.

  1. Make sure to use matching socket.io versions: On your client you use 2.4.0 , so install the same version on your server ( npm install socket.io@2.4.0 ).
  2. In the changelog for 2.4.0 you can see how you have to set cors options:
    const io = require('socket.io')(http, { origins: "http://localhost:5000" });
    You can't use "*" anymore, use your client domain. In newer versions the interface changed.

If you're not using version 2.4.0 , the problem could also be the "*" wildcard.

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