简体   繁体   中英

Socket.IO and Express

Here is my NodeJS server:

var express = require('express');

var app = express();

var port = process.env.PORT || 1337;
var server = app.listen(port);
var io = require('socket.io').listen(server);

io.sockets.on('connection', function(socket){
    console.log('A user connected to the chat!');

    socket.on('chat message', function(msg){
        console.log('message: ' + msg);
    });
});

And here is my client:

var socket = io();
socket.connect('http://server:1337', { autoConnect: true});
socket.on('connect',function() {
  socket.emit('chat message', "TEST");
});

And on my client side I get the following error in the console:

Cannot GET /socket.io/?EIO=3&transport=polling&t=LOIMkAR

You only need to use var socket = io.connect() , it will try to connect to the server automatically.

Unless you want to connect to a custom IP, which don't make much sense. io.connect() will do what you want to do.

After that you will use socket.emit for emitting events and socket.on for listening to events.

I've got this working with this setup similar to socket.io docs

var express = require('express');

var app = express();

var port = process.env.PORT || 1337;
var server = require('http').Server(app);
var io = require('socket.io')(server);

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