/// <summary> /// 发送封装传输包 /// </summary> /// <param name="packet">发送的传输包</param> public void SendSealedPacket(byte[] packet) { handler.SendSealedPacket(packet); foreach (PacketLogger logger in loggers) { logger.Write(packet, EndPoint); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="bytes">待发的数据</param> public void Send(byte[] bytes) { if (isOpen) { channelHandler.SendSealedPacket(bytes); } else { throw new TransmissionException("还没有连接服务器!"); } }
/// <summary> /// 交互函数 /// </summary> /// <param name="stateInfo"></param> internal void Exchange(object stateInfo) { try { isClose = false; do { byte[] rcvMsg = handler.ReceiveSealedPacket(); DictNode responseNode = HandlePacket(rcvMsg); byte[] sndMsg = BEncode.ByteArrayEncode(responseNode); handler.SendSealedPacket(sndMsg); if (isClose) { return; } } while (true); } catch (TdsException te) { Console.WriteLine("Tds Exception:{0}", te.Message); } catch (PacketException pe) { Console.WriteLine("Packet Exception:{0}", pe.Message); } catch (IOException ioe) { Console.WriteLine("IO Exception:{0}", ioe.Message); } catch (SocketException se) { Console.WriteLine("Socket Exception:{0}", se.Message); } catch (BEncodingException bee) { Console.WriteLine("BEncoding Exception:{0}", bee.Message); } finally { monitor.Unregister(handler); handler.Close(); } }
/// <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); } }
/// <summary> /// 发送数据包 /// </summary> /// <param name="packet">数据包</param> public void SendPacket(byte[] packet) { handler.SendSealedPacket(packet); }