/// <summary> /// Connect to the telnet server /// </summary> /// <returns>true if connection was successful</returns> public bool Connect() { // check for buffer if (this.buffer == null) this.buffer = new byte[RECEIVEBUFFERSIZE]; // virtual screen if (this.virtualScreen == null) this.virtualScreen = new VirtualScreen(this.vsWidth, this.vsHeight, 1, 1); // set the callbacks if (this.callBackReceive == null) this.callBackReceive = new AsyncCallback(ReadFromStream); if (this.callBackSend == null) this.callBackSend = new AsyncCallback(WriteToStream); // flags this.serverEcho = false; this.clientInitNaws = false; this.firstResponse = true; this.nawsNegotiated = false; this.forceLogout = false; // return physical connection if (this.tcpClient != null) return true; // we still have a connection -> ?? better reconnect ?? else { try { // TODO: Improve performance ...? // This is not working: IPAddress ipAddress = IPAddress.Parse(this.hostName); // IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, this.port); // because it addresses local endpoints this.tcpClient = new TcpClient(this.hostName, this.port); this.tcpClient.ReceiveTimeout = this.timeoutReceive; this.tcpClient.SendTimeout = this.timeoutSend; this.tcpClient.NoDelay = true; this.tcpClient.GetStream().BeginRead(this.buffer, 0, this.buffer.Length, this.callBackReceive, null); return true; } catch { this.tcpClient = null; return false; } } }
/// <summary> /// Closes external resources. /// Safe, can be called multiple times /// </summary> public void Close() { // physical connection if (this.tcpClient != null) { try { if (this.tcpClient.GetStream() != null) { // it is important to close the stream // because somehow tcpClient does not physically breaks down // the connection - on "one connection" telnet server the // server remains blocked if not doing it! try { this.tcpClient.GetStream().Close(); } catch { // further handling would go here } } this.tcpClient.Close(); this.tcpClient = null; } catch { this.tcpClient = null; } } this.virtualScreen = null; this.buffer = null; this.callBackReceive = null; this.callBackSend = null; this.forceLogout = false; }