如何在Node.js中使用WebSocket消息? [英] How can I consume WebSocket messages in Node.js?

查看:95
本文介绍了如何在Node.js中使用WebSocket消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是实现一个Node.Js服务器(我的服务器),它将连续读入从几个不同的websocket连接(源服务器,不同的URL)发出的消息,然后以某种方式处理这些消息。



我在ws(或wss)连接的情况下取得了成功,例如在这种情况下使用ws包:

  var  WebSocket = require('  ws'),
ws = new WebSocket(< span class =code-string>' wss://ws.pusherapp.com:443 / app / __ SECRET_API_CODE__');

ws.on(' message' function (message){
console .log(message);
});





但是如果源服务器使用socket.io库,则相同的方法不起作用,例如http://io.weplay.io(取自http://socket.io/demos/weplay/)。



有人能给我一个提示吗 - 我将欣赏任何编程语言 - 如何在我的服务器应用程序中使用来自不同源服务器的websocket消息?最好是以通用的方式,不依赖于WebSocket协议的具体实现。



非常感谢!

解决方案

包socket.io-client解决了这个问题:-)

  var  socket = require ('  socket.io-client')('  http://io.weplay.io'); 

socket.on(' connect' function (){
console .log(' < span class =code-string>已连接。');
});

socket.on(' message' function (data){
console .log(data);
});



由于代码中的拼写错误,我几个小时都无法解决它。 Uuuuf。


My task is to implement a Node.Js server ("my server") that will continuously read-in messages which are being emitted from several different websocket connections ("source servers", different URLs) and then process these messages somehow.

I was successful in the case of ws (or wss) connection, e.g. using the ws package in this case:

var WebSocket = require('ws'),
  ws = new WebSocket('wss://ws.pusherapp.com:443/app/__SECRET_API_CODE__');

ws.on('message', function(message) {
  console.log(message);
});



But the same approach does not work if the source server uses socket.io library, e.g. http://io.weplay.io (taken from http://socket.io/demos/weplay/).

Could somebody provide me a hint - I will appreciate any programming language - how to consume websocket messages from different source servers in my server application? Preferrably in an universal way, without depending on the concrete implementation of WebSocket protocol.

Thank you very much!

解决方案

Package socket.io-client solves the problem :-)

var socket = require('socket.io-client')('http://io.weplay.io');
 
socket.on('connect', function(){
  console.log('Connected.');
});
 
socket.on('message', function(data){
  console.log(data);
});


I could not solve it for several hours because of typo in the code. Uuuuf.


这篇关于如何在Node.js中使用WebSocket消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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