使用Node.js客户端访问Golang WebSocket服务器

6
我是一名NodeJS新手。假设我已经使用Golang的websocket包实现了一个回声服务器:
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()) } }
那么NodeJS客户端代码应该是什么样子的?

你确定你指的是 Node.js 而不是浏览器 WebSockets 吗? - beatgammit
浏览器可以使用WebSocket服务。但我感兴趣的是一个独立的Node.js应用程序是否可以使用它。 - Jeff Li
2个回答

23

作为WebSocket-Node库的作者,我可以向你保证,你不需要修改WebSocket-Node库的代码才能不使用子协议。

上面的示例代码错误地展示了在connect()函数的subprotocol参数中传递空字符串。如果您选择不使用子协议,则应将JavaScript的null值作为第二个参数传递,或者传递一个空数组(库能够按优先级降序建议多个受支持的子协议给远程服务器),但不能传递空字符串。


为什么这不是被接受的答案? - Rami Dabain
@brian-mckelvey 谢谢您的评论。我需要在ws url中进行基本身份验证,该怎么做? ws://f68a8efd-dc55-405d-b1f0-b4433477d52a:43093a7d-f563-43a7-8e46-56791cb1b92f@192.168.2.203:8011/v2/ws/websocket我尝试了这种方式,但是出现了以下错误。连接错误:错误:服务器响应了非101状态:401 响应头如下: 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 - Dibish
它对我有用的方式如下: var auth = "Basic " + new Buffer(uname + ":" + pwd).toString("base64"); var headers = { "Authorization" : auth }; - Dibish

10

我认为这个是你正在寻找的内容。以下是使用你的服务器代码的快速示例:

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");
为了使此功能正常工作,您需要修改lib/WebSocketCLient.js中的WebsocketClient代码。请注释掉这些行(在我的电脑上是第299-300行):
        //this.failHandshake("Expected a Sec-WebSocket-Protocol header.");
        //return;

由于某些原因,你提供的 WebSocket 库似乎没有发送 "Sec-Websocket-Protocol" 标头,或者至少客户端没有找到它。我还没有做太多测试,但应该在某处提交一个错误报告。

这里是使用 Go 客户端的示例:

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]))
}

2
如果您这样做,祝您升级好运。 - Rami Dabain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接