dsdxlibt98300 2013-02-18 09:39
浏览 324
已采纳

使用nodejs客户端访问golang websocket服务器

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
", 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条回答 默认 最新

  • doulu2576 2013-02-19 16:07
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。