如何从ws客户端连接socket.io? [英] How to connect with socket.io from a ws client?

查看:1242
本文介绍了如何从ws客户端连接socket.io?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的socket.io聊天示例,服务器端代码是这样的:

I have a very simple socket.io chat example, and the server side code is like this:

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');
});

客户端使用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开发工具中,我找到了真正的websocket网址,它应该是:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆