Is there a browserless websocket client for Node.js that does not need to use a browser?

后端 未结 5 1684
渐次进展
渐次进展 2020-12-08 17:13

Socket.IO, etc all require the using of browser on the client side....just wondering, how can we have browserless websocket client for node.js ?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 17:42

    Current Recommendation

    Use WebSocket-Node with my wrapper code (see below). As of this writing, no other public project that i know of supports the new hybi specification, so if you want to emulate current browser releases, you'll need WebSocket-Node. If you want to emulate older browsers, such as mobile Safari on iOS 4.2, you'll also need one of the other libraries listed below, but you'll have to manage "WebSocket" object name collisions yourself.

    A list of public WebSocket client implementations for node.js follows.

    Socket.IO

    The socket.io client-test WebSocket implementation does hixie draft 75/76, but as of this writing, not hybi 7+.

    https://github.com/LearnBoost/socket.io/blob/master/support/node-websocket-client/lib/websocket.js

    i'm asking if they intend to update to hybi 7+: http://groups.google.com/group/socket_io/browse_thread/thread/d27320502109d0be

    Node-Websocket-Client

    Peter Griess's "node-websocket-client" does hixie draft 75/76, but as of this writing, not hybi 7+.

    https://github.com/pgriess/node-websocket-client/blob/master/lib/websocket.js

    WebSocket-Node

    Brian McKelvey's WebSocket-Node has a client implementation for hybi 7-17 (protocol version 7-13), but the implementation does not provide a browser-style WebSocket object.

    https://github.com/Worlize/WebSocket-Node

    Here is the wrapper code I use to emulate the browser-style WebSocket object:

    /**
     * Wrapper for Worlize WebSocketNode to emulate the browser WebSocket object.
     */
    var WebSocketClient = require('./WorlizeWebSocketNode/lib/websocket').client;
    
    exports.WebSocket = function (uri) {
      var self = this;
      this.connection = null;
      this.socket = new WebSocketClient();
      this.socket.on('connect', function (connection) {
        self.connection = connection;
    
        connection.on('error', function (error) {
          self.onerror();
        });
    
        connection.on('close', function () {
          self.onclose();
        });
    
        connection.on('message', function (message) {
          if (message.type === 'utf8') {
            self.onmessage({data:message.utf8Data});
          }
        });
    
        self.onopen();
      });
      this.socket.connect(uri);
    }
    
    exports.WebSocket.prototype.send = function (data) {
      this.connection.sendUTF(data);
    }
    

    SockJS

    Just for reference, Marek Majkowski's SockJS does not include a node client. SockJS's client library is simply a browser dom wrapper.

    https://github.com/sockjs/sockjs-client

提交回复
热议问题