public void Disconnect() { if (_tcpClient != null) { _tcpClient.Close(); _tcpClient = null; _host = ""; _port = 0; NetUtil.Log("connection closed."); SysPost.InvokeMulticast(this, Disconnected); } }
public void Tick_ReceivingData() { try { while (_tcpClient.Available > 0) { byte[] cmdLenBuf = new byte[VarTracerConst.ByteSize_Int]; int cmdLenRead = _tcpClient.GetStream().Read(cmdLenBuf, 0, cmdLenBuf.Length); int cmdLen = BitConverter.ToInt32(cmdLenBuf, 0); if (cmdLenRead > 0 && cmdLen > 0) { byte[] buffer = new byte[cmdLen]; if (!NetUtil.ReadStreamData(_tcpClient, ref buffer)) { throw new Exception("Read Stream Data Error!"); } UsCmd cmd = new UsCmd(buffer); UsCmdExecResult result = _cmdParser.Execute(cmd); switch (result) { case UsCmdExecResult.Succ: break; case UsCmdExecResult.Failed: NetUtil.Log("net cmd execution failed: {0}.", new UsCmd(buffer).ReadNetCmd()); break; case UsCmdExecResult.HandlerNotFound: NetUtil.Log("net unknown cmd: {0}.", new UsCmd(buffer).ReadNetCmd()); break; } } } } catch (Exception ex) { DisconnectOnError("error detected while receiving data.", ex); } }
// Called when a connection to a server is established private void OnConnect(IAsyncResult asyncResult) { // Retrieving TcpClient from IAsyncResult TcpClient tcpClient = (TcpClient)asyncResult.AsyncState; try { if (tcpClient.Connected) // may throw NullReference { NetUtil.Log("connected successfully."); SysPost.InvokeMulticast(this, Connected); } else { throw new Exception(); } } catch (Exception ex) { DisconnectOnError("connection failed while handling OnConnect().", ex); } }
public void ExecuteCmd(string cmdText) { if (!IsConnected) { NetUtil.Log("not connected to server, command ignored."); return; } if (cmdText.Length == 0) { NetUtil.Log("the command bar is empty, try 'help' to list all supported commands."); return; } UsCmd cmd = new UsCmd(); cmd.WriteNetCmd(eNetCmd.CL_ExecCommand); cmd.WriteString(cmdText); Send(cmd); NetUtil.Log("command executed: [b]{0}[/b]", cmdText); }
private void OnGuardingTimeout(object sender, EventArgs e) { NetUtil.LogError("guarding timeout, closing connection..."); Disconnect(); }