2016-02-26 161 views
6

我有一个非常简单的socket.io聊天例如,服务器端代码是这样的:如何从ws客户端连接到socket.io?

https://github.com/js-demos/socketio-chat-demo/blob/master/index.js

var express = require('express'); 
var app = express(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

app.use(express.static('public')); 

io.on('connection', function(socket){ 
    socket.on('chat message', function(msg){ 
    io.emit('chat message', msg); 
    }); 
}); 

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 

通过io代码插座连接它的客户端和运作良好:

https://github.com/js-demos/socketio-chat-demo/blob/master/public%2Findex.html

<script> 
    var socket = io(); 
    $('form').submit(function(){ 
    socket.emit('chat message', $('#m').val()); 
    $('#m').val(''); 
    return false; 
    }); 
    socket.on('chat message', function(msg){ 
    $('#messages').append($('<li>').text(msg)); 
    }); 
</script> 

但我想使用一些其他的WebSocket客户端连接ŧ他的服务器,说,wscat

npm install -g wscat 
wscat ws://localhost:3000 

但它无法连接,与此错误:

error: Error: socket hang up 

我的网址ws://localhost:3000是错的?如何使它工作?

PS:你可以看到这个项目https://github.com/js-demos/socketio-chat-demo/和尝试

回答

18

从Chrome浏览器开发工具,我找到了真正的WebSocket URL,它应该是:

ws://localhost:3000/socket.io/?EIO=3&transport=websocket 

使用此URL与wscat效果很好

相关问题