/// <summary> /// 连接函数 /// </summary> /// <param name="host">服务器地址</param> /// <param name="port">服务器端口</param> public void Connect(string host, int port) { this.host = host; this.port = port; if (isOpen) { throw new TransmissionException("已经连接了服务器!"); } try { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(host, port); channelHandler = new PacketHandler(client); key = channelHandler.Key; iv = channelHandler.IV; byte[] handshakeMsg = HandshakeHandler.BuildHandshake(key, iv); channelHandler.SendNormalPacket(handshakeMsg); byte[] ackBytes = channelHandler.ReceiveSealedPacket(); if (HandshakeHandler.VerifyHandshake(ackBytes, key, iv)) { isOpen = true; } else { channelHandler.Close(); } } catch (SocketException se) { throw new TransmissionException(se.Message, se); } }
/// <summary> /// 处理客户端 /// </summary> /// <param name="socket">客户端套接字</param> private DoubleChannelClient HandleClient(Socket socket) { IPacketHandler channelHandler1 = new PacketHandler(socket); IPacketHandler channelHandler2 = null; try { byte[] openMsg = channelHandler1.ReceiveNormalPacket(); byte[] key, iv; int clientPort; string error; bool openSuccess = CheckOpenPacket(openMsg, out key, out iv, out clientPort, out error); if (openSuccess) { channelHandler1.SetKeyIV(key, iv); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress clientIPAddress = ((IPEndPoint)socket.RemoteEndPoint).Address; client.Connect(clientIPAddress, clientPort); channelHandler2 = new PacketHandler(client); channelHandler2.SetKeyIV(key, iv); byte[] handshakeMsg = HandshakeHandler.BuildHandshake(key, iv); channelHandler2.SendSealedPacket(handshakeMsg); byte[] rcvMsg = channelHandler1.ReceiveSealedPacket(); if (HandshakeHandler.VerifyHandshake(rcvMsg, key, iv) && !isStop) { Register(channelHandler1); Register(channelHandler2); return(new DoubleChannelClient(channelHandler1, channelHandler2, this)); } CloseHandler(channelHandler1); CloseHandler(channelHandler2); return(null); } throw new TransmissionException(error); } catch (SocketException se) { CloseHandler(channelHandler1); CloseHandler(channelHandler2); throw new TransmissionException(se.Message, se); } catch (IOException ioe) { CloseHandler(channelHandler1); CloseHandler(channelHandler2); throw new TransmissionException(ioe.Message, ioe); } catch (PacketException pe) { CloseHandler(channelHandler1); CloseHandler(channelHandler2); throw new TransmissionException(pe.Message, pe); } catch (BEncodingException bee) { CloseHandler(channelHandler1); CloseHandler(channelHandler2); throw new TransmissionException(bee.Message, bee); } }