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
740 views
in Technique[技术] by (71.8m points)

javascript - How to connect with socket.io from a ws client?

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

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>

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

Is my url ws://localhost:3000 is wrong? How to make it work?

PS: You can see this project https://github.com/js-demos/socketio-chat-demo/ and try it

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

From the Chrome Dev Tools, I found the real websocket url, it should be:

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

Use this url with wscat works well


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

...