public void Init(string host, int port, int index, bool littleEnd) { try { //if (inited) if (tcpSession != null) { tcpSession.Close(); tcpSession = null; } //if (!inited) { adapter = new NetAdapter(); adapter.SetEndianness(littleEnd); netClientId = index; socketStatus = SocketStatus.NotConnet; currentHost = host; currentPort = port; IPAddress ipEndPoint = IPAddress.Parse(currentHost); IPEndPoint ipEnd = new IPEndPoint(ipEndPoint, currentPort); tcpSession = new AsyncTcpSession(ipEnd); tcpSession.Connected += onConnected; tcpSession.Closed += onClosed; tcpSession.Error += onError; tcpSession.DataReceived += OnDataReceive; } } catch (System.Exception e) { Debugger.LogError("net client init exception->" + host + "^" + port + "^" + index + "^" + littleEnd + "^" + e.ToString()); } inited = true; }
private void bConnect_Click(object sender, EventArgs e) { if (bConnect.Text == "Disconnect") { if (client != null) { client.Close(); client = null; } bConnect.Text = "Connect"; return; } try { client = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(tServer.Text), Convert.ToInt32(tPort.Value))); #region // bind events client.Closed += client_Closed; client.Connected += client_Connected; client.DataReceived += client_DataReceived; client.Error += client_Error; #endregion AppendNotify("Connecting..."); bConnect.Text = "Disconnect"; client.Connect(); } catch (Exception ex) { AppendNotify("Connect failed: " + ex.Message); } }
internal IFuture Start() { lock (_rootSync) { if (_session != null && (_session.IsOpened || _session.SessionState == SessionState.Opening)) { return(null); } if (_session != null) { _session.Close(); _session = null; } if (_session == null) { _session = new AsyncTcpSession(_remoteEP, true, 5000, 10000, true); _session.PacketEncoder = new DefaultPacketEncoder(_messageBodyEncoder); _session.PacketDecoder = new DefaultPacketDecoder(_messageBodyDecoder); _session.ObjectReceived += SessionObjectReceived; _session.ExceptionCaught += SessionExceptionCaught; _session.StateChanged += SessionStateChanged; _session.Closed += SessionClosed; } return(_session.Open()); } }
/// <summary> /// 关闭连接 /// </summary> public void Close() { if (client != null) { if (client.IsConnected) { client.Close(); client = null; } } }
public void Close() { try { _asyncTcpSession.Close(); } catch (Exception e) { throw new Exception(e.ToString()); } }
void CloseClient(AsyncTcpSession tcpClient) { try { tcpClient.Close(); } catch (Exception ex) { AppendInfo("Close Client: " + ex.ToString()); } }
public void A_TestAsyncTcpSession() { AppServer appServer = new AppServer(); Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); Assert.IsTrue(appServer.Start()); appServer.NewRequestReceived += (s, e) => { Assert.AreEqual("Hello!", e.Key); byte[] bytesToSend = Encoding.UTF8.GetBytes("Welcome!"); s.Send(bytesToSend, 0, bytesToSend.Length); }; AsyncTcpSession asyncTcpSession = new AsyncTcpSession(); asyncTcpSession.ReceiveBufferSize = 8; AutoResetEvent sessionDataReceivedEvent = new AutoResetEvent(false); asyncTcpSession.DataReceived += (s, e) => { string message = Encoding.ASCII.GetString(e.Data); Assert.AreEqual("Welcome!", message); sessionDataReceivedEvent.Set(); }; AutoResetEvent connectedEvent = new AutoResetEvent(false); asyncTcpSession.Connected += (s, e) => { connectedEvent.Set(); }; asyncTcpSession.Connect(serverEndpoint); Assert.IsTrue(connectedEvent.WaitOne(timeout)); Assert.IsTrue(asyncTcpSession.IsConnected); byte[] data = (Encoding.ASCII.GetBytes("Hello!" + Environment.NewLine)); asyncTcpSession.Send(data, 0, data.Length); sessionDataReceivedEvent.WaitOne(timeout); asyncTcpSession.Close(); appServer.Stop(); }
public bool Stop() { lock (LockObj_IsConnection) { StopKeepAliveTimer(); if (_parseEngine != null) { _parseEngine.Stop(); Log.Info(string.Format("socket[{0}:{1}] parseEngine is stop", IpAddress, Port)); } if (IsConnection) { _clientSocket.Close(); LogOffSocketEvent(_clientSocket); _clientSocket = null; } return(true); } }
/// <summary> /// Close按钮单击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Btn_close_Click(object sender, RoutedEventArgs e) { tcpClient.Close(); CloseState(); }
private void OpenTcpThread(object arg) { try { int channelNumber = (int)arg; int index = 0; while (index < channelNumber) { try { //首先关闭当前的连接 if (tcpClient.IsConnected) { tcpClient.Close(); GlobalDataInterface.CommportConnectFlag = false; } else { GlobalDataInterface.CommportConnectFlag = false; } int SelId = m_ChanelIDList[index]; int m_InnerQualitySubsysindex = Commonfunction.GetSubsysIndex(SelId); //子系统索引 int m_InnerQualityChannelIndex = Commonfunction.GetChannelIndex(SelId); //子系统通道 int dataIndex = m_InnerQualitySubsysindex * ConstPreDefine.MAX_CHANNEL_NUM + m_InnerQualityChannelIndex; m_TcpChannelIndex = dataIndex; //当前选择的TCP通道索引 string ip = ConstPreDefine.LC_IP_ADDR_TEMPLATE + (dataIndex + 101); #region 网络Ping验证 Ping m_ping = new Ping(); PingReply pingReply = m_ping.Send(ip, 500); if (pingReply.Status != IPStatus.Success) { index++; continue; } //网络不通 #endregion tcpClient.Connect(new IPEndPoint(IPAddress.Parse(ip), ConstPreDefine.LC_PORT_NUM)); //建立index+1的通道连接 Thread.Sleep(500); if (GlobalDataInterface.CommportConnectFlag) { MessageDataSend(ConstPreDefine.SBC_INFO_REQ); //请求光谱仪指令 } Thread.Sleep(1000); //最后关闭当前的连接(仅在有需要时才打开连接) if (tcpClient.IsConnected) { tcpClient.Close(); GlobalDataInterface.CommportConnectFlag = false; } else { GlobalDataInterface.CommportConnectFlag = false; } } catch (Exception ex) { Trace.WriteLine("ProjectSetForm中函数OpenTcpThread的while循环出错,index=" + index.ToString() + ex); #if REALEASE GlobalDataInterface.WriteErrorInfo("ProjectSetForm中函数OpenTcpThread的while循环出错,index=" + index.ToString() + ex); #endif } index++; } } catch (Exception ex) { Trace.WriteLine("ProjectSetForm中函数OpenTcpThread出错" + ex); #if REALEASE GlobalDataInterface.WriteErrorInfo("ProjectSetForm中函数OpenTcpThread出错" + ex); #endif } }
public bool ProcessFrame(AsyncTcpSession session) { this.position = stream.Position; if (stream.Length == 1) { stream.Position = 0; Byte fin = (Byte)stream.ReadByte(); stream.Position = this.position; int opcode = (fin & 0xf); if (!Opcodes.IsValidCode(opcode)) { return(false); } Opcode = opcode; FrameFin = ((fin & 0x80) >> 7); ReaderStep = FrameReaderStep.FrameFin; curPosition = 1; } else if (stream.Length == 2) { stream.Position = 1; int frameMask = stream.ReadByte(); curPosition = stream.Position; FrameMask = ((frameMask & 0x80) >> 7); ReaderStep = FrameReaderStep.FrameMask; FramePayloadLength = frameMask & 0x7f; if (FramePayloadLength >= 0 && FramePayloadLength <= 0x7d) { //7位长 ReaderStep = FrameReaderStep.PayloadLength; } else if (FramePayloadLength == 0x7E) { //16位长 session.SetNoCheckCount(1); } else if (FramePayloadLength == 0x7F) { //64位长 session.SetNoCheckCount(7); } } else if (ReaderStep == FrameReaderStep.FrameMask) { stream.Position = curPosition; BinaryReader br = new BinaryReader(stream); if (FramePayloadLength == 0x7E) { //16位长 Byte[] tmpBytes = br.ReadBytes(2); tmpBytes = tmpBytes.Reverse().ToArray(); FramePayloadLength = BitConverter.ToUInt16(tmpBytes, 0); } else if (FramePayloadLength == 0x7F) { //64位长 Byte[] tmpBytes = br.ReadBytes(8); tmpBytes = tmpBytes.Reverse().ToArray(); FramePayloadLength = (long)BitConverter.ToUInt64(tmpBytes, 0); } curPosition = stream.Position; if (FramePayloadLength > MaxLength) { session.Close(); return(false); } ReaderStep = FrameReaderStep.PayloadLength; } if (ReaderStep == FrameReaderStep.PayloadLength) { if (FrameMask == 1) { session.SetNoCheckCount(3); ReaderStep = FrameReaderStep.FrameMaskingKey; return(true); } else { if (FramePayloadLength > 0) { session.SetNoCheckCount(FramePayloadLength - 1); DataReadTime = DateTime.Now; ReaderStep = FrameReaderStep.PayoutData; } return(true); } } else if (ReaderStep == FrameReaderStep.FrameMaskingKey) { stream.Position = curPosition; BinaryReader br = new BinaryReader(stream); FrameMaskingKey = br.ReadBytes(4); curPosition = stream.Position; if (FramePayloadLength > 0) { session.SetNoCheckCount(FramePayloadLength - 1); ReaderStep = FrameReaderStep.PayoutData; return(true); } else { ReaderStep = FrameReaderStep.PayoutData; } } //if (ReaderStep == FrameReaderStep.FrameMaskingKey) //{ // if (FramePayloadLength > 0) // { // session.SetNoCheckCount(FramePayloadLength - 1); // ReaderStep = FrameReaderStep.PayoutData; // return true; // } // else // { // ReaderStep = FrameReaderStep.PayoutData; // } //} if (ReaderStep == FrameReaderStep.PayoutData) { if (FramePayloadLength > 0) { stream.Position = curPosition; BinaryReader br = new BinaryReader(stream); if (FrameData != null && FrameData.Length > 0) { Byte[] tmpData = FrameData; logger.Trace("新建:{0}", tmpData.Length + FramePayloadLength); FrameData = new Byte[tmpData.Length + FramePayloadLength]; Array.Copy(tmpData, FrameData, tmpData.Length); Byte[] curData = br.ReadBytes((int)FramePayloadLength); if (FrameMask == 1) { curData.DecodeMask(FrameMaskingKey, 0, curData.Length); } Array.Copy(curData, 0, FrameData, tmpData.Length, curData.Length); } else { FrameData = br.ReadBytes((int)FramePayloadLength); if (FrameMask == 1) { FrameData.DecodeMask(FrameMaskingKey, 0, FrameData.Length); } } } if (FrameFin == 0) { ReaderStep = FrameReaderStep.ContinuationFrame; } else { DataReadTime = DateTime.MinValue; ReaderStep = FrameReaderStep.Completed; } } stream.Position = this.position; return(true); }