Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - Connect to Socket.IO server with specific path and namespace

My Node.js application is running at URL http://www.example.com/myapp/.

I have configured a Socket.IO server (version 1.3.5) with a custom namespace. Here is an example code snippet:

var server = http.createServer(...);
var io = socketio(server);
io
    .of('/a/b/c')
    .on('connection', function (socket) {
        socket.emit('update', {msg: '/a/b/c'});
    });

I can't figure out how to connect to this service from the client. My guesses (none of these is working):

io.connect('http://www.example.com/myapp/a/b/c');
io.connect('http://www.example.com', {path: '/myapp/a/b/c'});
io.connect('', {path: '/myapp/a/b/c'});
io.connect('http://www.example.com/a/b/c', {path: '/myapp'});
io.connect('http://www.example.com', {path: '/myapp/socket.io/a/b/c'});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On your server, don't forget to specify the path as well:

var io  = require('socket.io')(http, { path: '/myapp/socket.io'});

io
.of('/my-namespace')
.on('connection', function(socket){
    console.log('a user connected with id %s', socket.id);

    socket.on('my-message', function (data) {
        io.of('my-namespace').emit('my-message', data);
        // or socket.emit(...)
        console.log('broadcasting my-message', data);
    });
});

On your client, don't confuse namespace and path:

var socket = io('http://www.example.com/my-namespace', { path: '/myapp/socket.io'});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...