问题描述
我有一个很简单的socket.io聊天例子,服务端代码是这样的:
I have a very simple socket.io chat example, and the server side code is like this:
https://github.com/js-演示/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');
});
客户端使用socket io代码连接它并且运行良好:
The client side using the socket io code to connect it and is working well:
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
:
But I want to use some other websocket client to connect the server, say, wscat
:
npm install -g wscat
wscat ws://localhost:3000
但它无法连接,出现此错误:
But it can't connect, with this error:
error: Error: socket hang up
我的网址 ws://localhost:3000
是错误的吗?如何让它发挥作用?
Is my url ws://localhost:3000
is wrong? How to make it work?
PS:你可以看到这个项目https://github.com/js-demos/socketio-chat-demo/ 试试看
PS: You can see this project https://github.com/js-demos/socketio-chat-demo/ and try it
推荐答案
从 Chrome Dev Tools 中找到了真正的 websocket url,应该是:
From the Chrome Dev Tools, I found the real websocket url, it should be:
ws://localhost:3000/socket.io/?EIO=3&transport=websocket
在 wscat 中使用这个 url 效果很好
Use this url with wscat works well
这篇关于如何从 ws 客户端连接 socket.io?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!