/// <summary> /// 链接远端 /// </summary> /// <param name="remoteHostname"> 远端地址</param> /// <param name="remotePort">远端端口</param> public void Connect(string remoteHostname, int remotePort) { //建立KCP,并绑定回调 channel = new KChannel(conv, client, remoteHostname, remotePort) { OnRecive = OnReciveCallBack }; channel.OnConnectState = OnConnectState; }
/// <summary> /// 接收消息线程 /// </summary> private void OnRecive(IAsyncResult ar) { try { remoteEndPoint = null; byte[] buf = client.EndReceive(ar, ref remoteEndPoint); //如果缓冲区为null 或 长度少于等于0,则断线 if (buf == null || buf.Length <= 0) { Dispose(); Debug.LogError("kcp buff is None"); return; } //获取会话conv UInt32 conv = 0; KCP.ikcp_decode32u(buf, 0, ref conv); //查找信道池,没有则建立新的 KChannel channel; if (!channels.TryGetValue(conv, out channel)) { channel = new KChannel(conv, client, remoteEndPoint) { OnRecive = OnRecive }; channel.OnConnectState = OnConnectState; channels.Add(conv, channel); } channel.Input(buf); //再次调用异步接收 client.BeginReceive(OnRecive, null); } catch (Exception) { //TODO 触发此处异常,一般由于客户端主动关闭致使S端无法返回数据包到C端。 //TODO 服务器在此类异常中不需要关闭,只需要处理掉断开连接的C端 } }