private void RaknetUdpPeerClient_OnConnectionRequestAccepted(string address, ushort port) { if (address == _natServerAddress.Address && port == _natServerAddress.Port) { //OpenNAT RakNetGUID peerServerRakNetGUID = new RakNetGUID(_udpPeerServerGuid); RakNetGUID myGuid = rakPeer.GetMyGUID(); if (myGuid.g != _udpPeerServerGuid) { natPunchthroughClient.OpenNAT(peerServerRakNetGUID, new SystemAddress(address, port)); } } else if (address == _coordinatorAddress.Address && port == _coordinatorAddress.Port) { udpProxyClient.SetResultHandler(new MyUDPProxyClientResultHandler()); SystemAddress coordinatorAddress = new SystemAddress(); coordinatorAddress.SetBinaryAddress(_coordinatorAddress.Address); coordinatorAddress.SetPortHostOrder(_coordinatorAddress.Port); udpProxyClient.RequestForwarding(coordinatorAddress, rakPeer.GetMyBoundAddress(), new SystemAddress(_peerServerAddress.Address, _peerServerAddress.Port), 7000); } else if (_proxyServerAddress != null && address == _proxyServerAddress.Address && port == _proxyServerAddress.Port) { _isConnectPeerServer = true; new Thread(n => { OnConnect(address, port, this); }) { IsBackground = true, Priority = ThreadPriority.Highest }.Start(); //代理连接成功,对_peerServerAddress重新赋值,该值实际是proxy的一个临时地址,通过该值直接发送消息给peerServer,但通过代理的方式要持续发送消息给proxy才能保持连接,如果一段时间内不发送消息,则连接主动断开 _peerServerAddress = new RaknetIPAddress(address, port); //开启线程,持续向proxy发送消息,只能发送一个字节,并且消息类型必须为 DefaultMessageIDTypes.ID_USER_PACKET_ENUM ThreadPool.QueueUserWorkItem(obj => { isProxyMsgSending = true; while (true) { if (!isProxyMsgSending) { break; } RaknetExtension.WriteInfo("dddddddd"); //循环发送消息以保持连接 var tempByte = new byte[] { (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM }; rakPeer.Send(tempByte, tempByte.Length, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress(_peerServerAddress.Address, _peerServerAddress.Port)), false); Thread.Sleep(4000); } }); } else { _isConnectPeerServer = true; new Thread(n => { OnConnect(address, port, this); }) { IsBackground = true, Priority = ThreadPriority.Highest }.Start(); //通过NAT与peerServer连接成功后,立即断开与natServer的连接 rakPeer.CloseConnection(new AddressOrGUID(new SystemAddress(_natServerAddress.Address, _natServerAddress.Port)), true); } }