您的位置:首页 > 编程语言 > Java开发

.net , java webSocket 连接 Socket.io (1.4.4版本) 问题

2016-01-19 11:06 597 查看
  .net版Socketio4net类库和java版socket.io-java-client类库 连接socket.io 1.4版本都不行,网上大多是socket.io 0.9版本的,socket.io 更新之后就不支持了。本人已研究

成功连接socket.io 1.4版本的方法,例子采用C#。

  一、socket.io 几个重要要文件

   1、node_modules\socket.io\node_modules\engine.io\node_modules\engine.io-parser\lib\index.js  

var packets = exports.packets = {
open:     0    // non-ws
, close:    1    // non-ws
, ping:     2
, pong:     3
, message:  4
, upgrade:  5
, noop:     6
};


    这几个是定义消息类型的 websocket连接的时候在open事件里需要发送一个send("5[\"simple\",{\"name\":\"simple\"}]"); 类型为5的消息。

    

public void Connect()
{
lock (padLock)
{
if (!(this.ReadyState == WebSocketState.Connecting || this.ReadyState == WebSocketState.Open))
{
try
{
this.ConnectionOpenEvent.Reset();
this.HandShake = this.requestHandshake(uri);// perform an initial HTTP request as a new, non-handshaken connection

if (this.HandShake == null || string.IsNullOrWhiteSpace(this.HandShake.SID) || this.HandShake.HadError)
{
this.LastErrorMessage = string.Format("Error initializing handshake with {0}", uri.ToString());
this.OnErrorEvent(this, new ErrorEventArgs(this.LastErrorMessage, new Exception()));
}
else
{
String sss = "ws://127.0.0.1:3000/socket.io/?eio=3&t=124324324324&transport=websocket&sid=" + this.HandShake.SID;
//sss = "ws://127.0.0.1:3000/socket.io/?transport=polling&t=12434324324324&sid=" + this.HandShake.SID;
//string.Format("{0}://{1}:{2}/socket.io/1/websocket/{3}", wsScheme, uri.Host, uri.Port, this.HandShake.SID)
string wsScheme = (uri.Scheme == Uri.UriSchemeHttps ? "wss" : "ws");
this.wsClient = new WebSocket(
sss,
string.Empty,
this.socketVersion);
this.wsClient.EnableAutoSendPing = false; // #4 tkiley: Websocket4net client library initiates a websocket heartbeat, causes delivery problems
this.wsClient.Opened += this.wsClient_OpenEvent;
this.wsClient.MessageReceived += this.wsClient_MessageReceived;
this.wsClient.Error += this.wsClient_Error;

this.wsClient.Closed += wsClient_Closed;

this.wsClient.Open();
}
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Connect threw an exception...{0}", ex.Message));
this.OnErrorEvent(this, new ErrorEventArgs("SocketIO.Client.Connect threw an exception", ex));
}
}
}
}


View Code
    连接之后在open 事件里需要发送一个类型为5(upgrade 心跳)的消息websocket.send("5[\"simple\",{\"name\":\"simple\"}]");,然后websocket会收到一个“40”消息,

   40代表连接功能了,可以进行通信了。

  一般发送消息的格式为:"42[\"simple\",{\"name\":\"tstssss\"}]"

  42:代表消息类型,simple为socket.io的事件名称。

  四、定时发送心跳数据

      授权的时候能获取到"pingInterval":25000,"pingTimeout":60000 心跳间隔和超时的时间,需要每隔 pingInterval 时间 发送一次心跳数据才能保存不断开连接。

    send("5:::");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: