StunMessage Query(ISocketClient client, StunMessage request, IPEndPoint remoteEndPoint) { Packet pk = null; try { if (client.Local.IsTcp) { // Tcp协议不支持更换IP或者端口 if (request.ChangeIP || request.ChangePort) { return(null); } //if (!client.Connected) client.Connect(remoteEndPoint); //client.Send(request.ToArray()); } //else // client.SendTo(request.ToArray(), remoteEndPoint); WriteLog("查询 {0} =>{1}", request, remoteEndPoint); client.Remote.EndPoint = remoteEndPoint; client.Send(request.ToArray()); pk = client.Receive(); if (pk == null || pk.Count == 0) { return(null); } } catch { return(null); } var rs = StunMessage.Read(pk.GetStream()); //if (rs != null && rs.Type != StunMessageType.BindingResponse) return null; if (rs == null) { return(null); } // 不是同一个会话不要 if (rs.TransactionID.CompareTo(request.TransactionID) != 0) { return(null); } // 不是期望的响应不要 if (rs.Type != (StunMessageType)((UInt16)request.Type | 0x0100)) { return(null); } return(rs); }
/// <summary>接收到数据时</summary> /// <param name="session"></param> /// <param name="pk"></param> protected override void OnReceive(INetSession session, Packet pk) { if (pk.Total > 0) { var remote = session.Remote; //if (remote == null && session != null) remote = session.RemoteEndPoint; var request = StunMessage.Read(pk.GetStream()); WriteLog("{0} {1} {2}{3}", request.Type, remote, request.ChangeIP ? " ChangeIP" : "", request.ChangePort ? " ChangePort" : ""); // 如果是兄弟服务器发过来的,修正响应地址 switch (request.Type) { case StunMessageType.BindingRequest: //case StunMessageType.BindingResponse: request.Type = StunMessageType.BindingRequest; if (request.ResponseAddress != null) { remote.EndPoint = request.ResponseAddress; } break; case StunMessageType.SharedSecretRequest: //case StunMessageType.SharedSecretResponse: request.Type = StunMessageType.SharedSecretRequest; if (request.ResponseAddress != null) { remote.EndPoint = request.ResponseAddress; } break; default: break; } // 是否需要发给伙伴 if (request.ChangeIP) { //if (Partner != null && !Partner.Equals(session.Host.LocalEndPoint.GetRelativeEndPoint(Partner.Address))) //{ // // 发给伙伴 // request.ChangeIP = false; // // 记住对方的地址 // request.ResponseAddress = remote.EndPoint; // //session.Send(request.GetStream(), Partner); // var us = session.Host as UdpServer; // if (us != null) // { // //us.CreateSession(Partner).Send(request.GetStream()); // us.Send(request.GetStream(), Partner); // } // return; //} // 如果没有伙伴地址,采用不同端口代替 request.ChangePort = true; } // 开始分流处理 switch (request.Type) { case StunMessageType.BindingRequest: //case StunMessageType.BindingResponse: OnBind(request, session.Session); break; case StunMessageType.SharedSecretRequest: break; default: break; } } }