我想这就是你要找的。使用您的服务器代码的快速示例:
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
. 注释掉这些行(我机器上的第 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]))
}