Exemple #1
0
        /// <summary>
        /// 连接函数
        /// </summary>
        /// <param name="host">服务器地址</param>
        /// <param name="port">服务器端口</param>
        public void Connect(string host, int port)
        {
            if (isOpen)
            {
                throw new TransmissionException("已经连接了服务器!");
            }
            try
            {
                Socket     server         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Any, clientPort);
                server.Bind(serverEndPoint);
                server.Listen(1);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(host, port);
                channelHandler1 = new PacketHandler(client);
                key             = channelHandler1.Key;
                iv = channelHandler1.IV;

                byte[] openBytes = BuildHandshakeMessage();
                channelHandler1.SendNormalPacket(openBytes);

                Socket socket = server.Accept();
                channelHandler2 = new PacketHandler(socket);
                channelHandler2.SetKeyIV(key, iv);
                byte[] ackMsg = channelHandler2.ReceiveSealedPacket();
                if (HandshakeHandler.VerifyHandshake(ackMsg, key, iv))
                {
                    isOpen = true;
                    channelHandler1.SendSealedPacket(ackMsg);
                }
                else
                {
                    channelHandler1.Close();
                    channelHandler2.Close();
                }
            }
            catch (SocketException se)
            {
                throw new TransmissionException(se.Message, se);
            }
        }
Exemple #2
0
        /// <summary>
        /// 检验打开数据包
        /// </summary>
        /// <param name="packet">打开数据包</param>
        /// <returns>如果打开成功,返回ture,否则返回false</returns>
        private bool CheckOpenPacket(byte[] packet)
        {
            DictNode openPacket = (DictNode)BEncode.Decode(packet);
            int      code       = ((IntNode)openPacket["code"]).Value;

            switch (code)
            {
            case 1:
                byte[] key = ((BytesNode)openPacket["key"]).ByteArray;
                byte[] iv  = ((BytesNode)openPacket["iv"]).ByteArray;
                handler.SetKeyIV(key, iv);
                return(true);

            case 6:
                string messag = ((BytesNode)openPacket["message"]).StringText;
                throw new DbProxyException(messag);

            default:
                throw new DbProxyException("错误的消息代码");
            }
        }
Exemple #3
0
 public void SetKeyIV(byte[] key, byte[] iv)
 {
     handler.SetKeyIV(key, iv);
 }