C#使用TcpClient实现telnet功能

  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Text; 
  4. using System.Net.Sockets; 
  5.  
  6. namespace testTelnet 
  7.     enum Verbs 
  8.     { 
  9.         WILL = 251, 
  10.         WONT = 252, 
  11.         DO = 253, 
  12.         DONT = 254, 
  13.         IAC = 255 
  14.     } 
  15.  
  16.     enum Options 
  17.     { 
  18.         SGA = 3 
  19.     } 
  20.  
  21.     class TelnetConnection 
  22.     { 
  23.         TcpClient tcpSocket; 
  24.  
  25.         int TimeOutMs = 1*1000; 
  26.  
  27.         public TelnetConnection(String Hostname, int Port) 
  28.         { 
  29.             tcpSocket = new TcpClient(Hostname, Port); 
  30.              
  31.         } 
  32.  
  33.         public string Login(string Username, string Password, int LoginTimeOutMs) 
  34.         { 
  35.             int oldTimeOutMs = TimeOutMs; 
  36.             TimeOutMs = LoginTimeOutMs; 
  37.             string s = Read(); 
  38.             if (!s.TrimEnd().EndsWith(":")) 
  39.                 throw new Exception("Failed to connect : no login prompt"); 
  40.             WriteLine(Username); 
  41.  
  42.             s += Read(); 
  43.             if (!s.TrimEnd().EndsWith(":")) 
  44.                 throw new Exception("Failed to connect : no password prompt"); 
  45.             WriteLine(Password); 
  46.  
  47.             s += Read(); 
  48.             TimeOutMs = oldTimeOutMs; 
  49.              
  50.             return s; 
  51.         } 
  52.  
  53.         public void DisConnect() 
  54.         { 
  55.             if (tcpSocket != null
  56.             { 
  57.                 if (tcpSocket.Connected) 
  58.                 { 
  59.                     tcpSocket.Client.Disconnect(true); 
  60.                 } 
  61.             } 
  62.         } 
  63.  
  64.         public void WriteLine(string cmd) 
  65.         { 
  66.             Write(cmd + "\r\n"); 
  67.         } 
  68.  
  69.         public void Write(string cmd) 
  70.         { 
  71.             if (!tcpSocket.Connected) return
  72.  
  73.             byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF", "\0xFF\0xFF")); 
  74.             tcpSocket.GetStream().Write(buf, 0, buf.Length); 
  75.         } 
  76.  
  77.         public string Read() 
  78.         { 
  79.             if (!tcpSocket.Connected) return null
  80.             StringBuilder sb = new StringBuilder(); 
  81.             do 
  82.             { 
  83.                 ParseTelnet(sb); 
  84.                 System.Threading.Thread.Sleep(TimeOutMs); 
  85.             } while (tcpSocket.Available > 0); 
  86.  
  87.             return ConvertToGB2312(sb.ToString()); 
  88.         } 
  89.  
  90.         public bool IsConnected 
  91.         { 
  92.             get { return tcpSocket.Connected; } 
  93.         } 
  94.  
  95.         void ParseTelnet(StringBuilder sb) 
  96.         { 
  97.             while (tcpSocket.Available > 0) 
  98.             { 
  99.                 int input = tcpSocket.GetStream().ReadByte(); 
  100.                 switch (input) 
  101.                 { 
  102.                     case -1: 
  103.                         break
  104.                     case (int)Verbs.IAC: 
  105.                         // interpret as command 
  106.                         int inputverb = tcpSocket.GetStream().ReadByte(); 
  107.                         if (inputverb == -1) break
  108.                         switch (inputverb) 
  109.                         { 
  110.                             case (int)Verbs.IAC: 
  111.                                 //literal IAC = 255 escaped, so append char 255 to string 
  112.                                 sb.Append(inputverb); 
  113.                                 break
  114.                             case (int)Verbs.DO: 
  115.                             case (int)Verbs.DONT: 
  116.                             case (int)Verbs.WILL: 
  117.                             case (int)Verbs.WONT: 
  118.                                 // reply to all commands with "WONT", unless it is SGA (suppres go ahead) 
  119.                                 int inputoption = tcpSocket.GetStream().ReadByte(); 
  120.                                 if (inputoption == -1) break
  121.                                 tcpSocket.GetStream().WriteByte((byte)Verbs.IAC); 
  122.                                 if (inputoption == (int)Options.SGA) 
  123.                                     tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL : (byte)Verbs.DO); 
  124.                                 else 
  125.                                     tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT); 
  126.                                 tcpSocket.GetStream().WriteByte((byte)inputoption); 
  127.                                 break
  128.                             default
  129.                                 break
  130.                         } 
  131.                         break
  132.                     default
  133.                         sb.Append((char)input); 
  134.                         break
  135.                 } 
  136.             } 
  137.         } 
  138.  
  139.         private string ConvertToGB2312(string str_origin) 
  140.         { 
  141.             char[] chars = str_origin.ToCharArray(); 
  142.             byte[] bytes = new byte[chars.Length]; 
  143.             for (int i = 0; i < chars.Length; i++) 
  144.             { 
  145.                 int c = (int)chars[i]; 
  146.                 bytes[i] = (byte)c; 
  147.             } 
  148.             Encoding Encoding_GB2312 = Encoding.GetEncoding("GB2312"); 
  149.             string str_converted = Encoding_GB2312.GetString(bytes); 
  150.             return str_converted; 
  151.         } 
  152.     } 
// minimalistic telnet implementation
// conceived by Tom Janssens on 2007/06/06  for codeproject
//
// http://www.corebvba.be



using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace testTelnet
{
    enum Verbs
    {
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    enum Options
    {
        SGA = 3
    }

    class TelnetConnection
    {
        TcpClient tcpSocket;

        int TimeOutMs = 1*1000;

        public TelnetConnection(String Hostname, int Port)
        {
            tcpSocket = new TcpClient(Hostname, Port);
            
        }

        public string Login(string Username, string Password, int LoginTimeOutMs)
        {
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
            string s = Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no login prompt");
            WriteLine(Username);

            s += Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no password prompt");
            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;
            
            return s;
        }

        public void DisConnect()
        {
            if (tcpSocket != null)
            {
                if (tcpSocket.Connected)
                {
                    tcpSocket.Client.Disconnect(true);
                }
            }
        }

        public void WriteLine(string cmd)
        {
            Write(cmd + "\r\n");
        }

        public void Write(string cmd)
        {
            if (!tcpSocket.Connected) return;

            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF", "\0xFF\0xFF"));
            tcpSocket.GetStream().Write(buf, 0, buf.Length);
        }

        public string Read()
        {
            if (!tcpSocket.Connected) return null;
            StringBuilder sb = new StringBuilder();
            do
            {
                ParseTelnet(sb);
                System.Threading.Thread.Sleep(TimeOutMs);
            } while (tcpSocket.Available > 0);

            return ConvertToGB2312(sb.ToString());
        }

        public bool IsConnected
        {
            get { return tcpSocket.Connected; }
        }

        void ParseTelnet(StringBuilder sb)
        {
            while (tcpSocket.Available > 0)
            {
                int input = tcpSocket.GetStream().ReadByte();
                switch (input)
                {
                    case -1:
                        break;
                    case (int)Verbs.IAC:
                        // interpret as command
                        int inputverb = tcpSocket.GetStream().ReadByte();
                        if (inputverb == -1) break;
                        switch (inputverb)
                        {
                            case (int)Verbs.IAC:
                                //literal IAC = 255 escaped, so append char 255 to string
                                sb.Append(inputverb);
                                break;
                            case (int)Verbs.DO:
                            case (int)Verbs.DONT:
                            case (int)Verbs.WILL:
                            case (int)Verbs.WONT:
                                // reply to all commands with "WONT", unless it is SGA (suppres go ahead)
                                int inputoption = tcpSocket.GetStream().ReadByte();
                                if (inputoption == -1) break;
                                tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                if (inputoption == (int)Options.SGA)
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL : (byte)Verbs.DO);
                                else
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT);
                                tcpSocket.GetStream().WriteByte((byte)inputoption);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        sb.Append((char)input);
                        break;
                }
            }
        }

        private string ConvertToGB2312(string str_origin)
        {
            char[] chars = str_origin.ToCharArray();
            byte[] bytes = new byte[chars.Length];
            for (int i = 0; i < chars.Length; i++)
            {
                int c = (int)chars[i];
                bytes[i] = (byte)c;
            }
            Encoding Encoding_GB2312 = Encoding.GetEncoding("GB2312");
            string str_converted = Encoding_GB2312.GetString(bytes);
            return str_converted;
        }
    }
}


启动代码

  1. static void Main(string[] args) 
  2.         { 
  3.             //create a new telnet connection to hostname "gobelijn" on port "23" 
  4.             TelnetConnection tc = new TelnetConnection("127.0.0.1", 23); 
  5.  
  6.             //login with user "root",password "rootpassword", using a timeout of 100ms,  
  7.             //and show server output 
  8.             string s = tc.Login("administrator", "pw", 100); 
  9.             Console.Write(s); 
  10.  
  11.             // server output should end with "{1}quot; or ">", otherwise the connection failed 
  12.             string prompt = s.TrimEnd(); 
  13.             prompt = s.Substring(prompt.Length - 1, 1); 
  14.             if (prompt != ":"
  15.                 throw new Exception("Connection failed"); 
  16.  
  17.             prompt = ""
  18.  
  19.             // while connected 
  20.             while (tc.IsConnected && prompt.Trim() != "exit"
  21.             { 
  22.                 // display server output 
  23.                 Console.Write(tc.Read()); 
  24.  
  25.                 // send client input to server 
  26.                 prompt = Console.ReadLine(); 
  27.                 tc.WriteLine(prompt); 
  28.  
  29.                 // display server output 
  30.                 Console.Write(tc.Read()); 
  31.             } 
  32.  
  33.             Console.WriteLine("***DISCONNECTED"); 
  34.             Console.ReadLine(); 
  35.  
  36.         } 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的异步TCPClient是一种用于进行网络通信的类。它允许你在进行网络连接、发送和接收数据时,使用异步操作来提高应用程序的性能和响应性。 要使用异步TCPClient,你需要使用C#的异步编程模型(Async/Await)。以下是使用异步TCPClient的一些基本步骤: 1. 创建一个TCPClient对象,并指定要连接的远程主机和端口号。 2. 使用TCPClient对象的ConnectAsync方法,以异步方式连接到远程主机。 3. 一旦连接成功,你可以使用TCPClient对象的GetStream方法获取与远程主机进行通信的网络流。 4. 对于发送数据,你可以使用网络流的WriteAsync方法以异步方式发送字节数据或字符串。 5. 对于接收数据,你可以使用网络流的ReadAsync方法以异步方式接收字节数据或字符串。 下面是一个简单的示例代码,展示了如何使用异步TCPClient发送和接收数据: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; public class AsyncTcpClient { public static async Task Main() { // 远程主机的IP地址和端口号 string ipAddress = "127.0.0.1"; int port = 12345; // 创建TCPClient对象并连接到远程主机 TcpClient client = new TcpClient(); await client.ConnectAsync(IPAddress.Parse(ipAddress), port); // 获取与远程主机进行通信的网络流 NetworkStream stream = client.GetStream(); // 发送数据 string messageToSend = "Hello, server!"; byte[] sendData = Encoding.UTF8.GetBytes(messageToSend); await stream.WriteAsync(sendData, 0, sendData.Length); // 接收数据 byte[] receiveData = new byte
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值