6

I am a newbie to NodeJS. Assume that I have a echo server implemented with Golang's websocket package:

package main

import (
    "code.google.com/p/go.net/websocket"
    "log"
    "net/http"
)

func EchoServer(ws *websocket.Conn) {
    var msg string
    websocket.Message.Receive(ws, &msg)
    log.Printf("Message Got: %s\n", msg)
    websocket.Message.Send(ws, msg)
}

func main() {
    http.Handle("/echo", websocket.Handler(EchoServer))
    err := http.ListenAndServe(":8082", nil)
    if err != nil {
        panic(err.Error())
    }
}

What should the nodejs client code look like ?

2
  • Are you sure you mean node.js and not browser WebSockets? Commented Feb 19, 2013 at 6:55
  • The browser can consume the websocket service. But what I am interested in is whether a standalone nodejs app can consume it. Commented Feb 19, 2013 at 9:11

2 Answers 2

23

As the author of the WebSocket-Node library, I can assure you that you do not need to modify the WebSocket-Node library code in order to not use a subprotocol.

The example code above incorrectly shows passing an empty string for the subprotocol parameter of the connect() function. If you are choosing not to use a subprotocol, you should pass JavaScript's null value as the second parameter, or an empty array (the library is able to suggest multiple supported subprotocols to the remote server in order of descending desirability), but not an empty string.

Sign up to request clarification or add additional context in comments.

3 Comments

Like seriously why isn't this is the accepted answer ?
@brian-mckelvey Thank you for you comment. I need basic Authentication in ws url, How to do it? ws://f68a8efd-dc55-405d-b1f0-b4433477d52a:[email protected]:8011/v2/ws/websocket Tried this way but got following Error. Connect Error: Error: Server responded with a non-101 status: 401 Response Headers Follow: www-authenticate: Basic realm="Authentication required" date: Thu, 08 Sep 2016 06:20:03 GMT content-length: 25 content-type: text/plain; charset=utf-8
Its worked for me like following way var auth = "Basic " + new Buffer(uname + ":" + pwd).toString("base64"); var headers = { "Authorization" : auth };
10

I think this is what you're looking for. Quick example using your server code:

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket client connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });

    connection.sendUTF("Hello world");
});

client.connect('ws://127.0.0.1:8082/echo', "", "http://localhost:8082");

To get this to work, you'll need to modify the WebsocketClient code in lib/WebSocketCLient.js. Comment these lines out (lines 299-300 on my machine):

        //this.failHandshake("Expected a Sec-WebSocket-Protocol header.");
        //return;

For some reason the websocket library you provided doesn't seem to send the "Sec-Websocket-Protocol" header, or at least the client doesn't find it. I haven't done too much testing, but a bug report should probably be filed somewhere.

Here's an example using a Go client:

package main

import (
    "fmt"
    "code.google.com/p/go.net/websocket"
)

const message = "Hello world"

func main() {
    ws, err := websocket.Dial("ws://localhost:8082/echo", "", "http://localhost:8082")
    if err != nil {
        panic(err)
    }
    if _, err := ws.Write([]byte(message)); err != nil {
        panic(err)
    }
    var resp = make([]byte, 4096)
    n, err := ws.Read(resp)
    if err != nil {
        panic(err)
    }
    fmt.Println("Received:", string(resp[0:n]))
}

1 Comment

Correct answer below... If you do it this way good luck upgrading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.