예제 #1
0
        /// <summary>
        /// 创建一个客户端超级套接字
        /// <para>客户端会尝试连接3次,如果3次都失败则触发连接失败回调</para>
        /// </summary>
        /// <param name="ip">连接地址</param>
        /// <param name="port">连接端口</param>
        /// <param name="listener">监听器</param>
        /// <param name="config">配置</param>
        /// <returns></returns>
        public static HyperSocket CreateClient(string ip, uint port, IHyperSocketClient listener, HyperSocketConfig config = null)
        {
            try
            {
                if (config == null)
                {
                    config = new HyperSocketConfig();
                }
                var hyperSocket = new HyperSocket(false, ip, port, 0, 0, config);
                hyperSocket.cntListener = listener;
                // 开始发起连接
                hyperSocket.tcpClient = new HyperSocketClientModule(ip, (int)port, (int)config.TcpReceiveSize, ProtocolType.Tcp, hyperSocket);
                hyperSocket.tcpClient.SetListener(listener);
                hyperSocket.tcpClient.Init(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, hyperSocket.tcpClient);
                // 发送验证标签
                hyperSocket.tcpClient.Send(FirstConnectBytes);

                return(hyperSocket);
            }
            catch (Exception ex)
            {
                listener.SocketError(null, ex);
                return(null);
            }
        }
예제 #2
0
 /// <summary>
 /// 初始化
 /// </summary>
 internal void InitializeUdpClient(byte[] data)
 {
     try
     {
         if (data.Length == 8 && data[4] == (byte)(data[0] + data[1]) && data[5] == (byte)(data[2] + data[3]) && data[6] == (byte)(data[0] + data[3]) && data[7] == (byte)(data[1] + data[2]))
         {
             ushort udpPort = (ushort)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF));
             SessionId = (ushort)(((data[2] & 0xFF) << 8) | (data[3] & 0xFF));
             UdpPort   = udpPort;
             udpClient = new HyperSocketClientModule(ip, udpPort, (int)config.UdpReceiveSize, ProtocolType.Udp, this);
             udpClient.SetListener(cntListener);
             // 返回验证UDP连接
             if (udpClient.Init(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp, udpClient))
             {
                 long verifyCode = SessionId * (udpPort / 10);
                 udpClient.SendKcp(Encoding.UTF8.GetBytes(verifyCode.ToString()));
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         cntListener.SocketError(this, ex);
     }
     // 没有进入最内部逻辑则直接关闭
     Close();
 }
 public void SocketException(Exception exception)
 {
     if (listener != null)
     {
         listener.SocketError(hyperSocket, exception);
     }
     if (hyperSocket != null)
     {
         hyperSocket.Close();
     }
 }