见过这类的实现,但是不知道该怎么表述,所以标题可能有不当的地方。
具体表述如下:已经创建了一个服务,为了跟踪服务的执行,做很很多输出信息,一般我是输出到磁盘的一个文本文件里来查看,现在我想telnet登录到这个服务上,可以列出这个服务的一些写好的方法,在telnet的客户端输入一个命令后,这些跟踪信息就从服务器直接输出到telnet的客户端。按我的理解就好像把服务里的输出信息做一个开关,一旦客户端输入一个命令后,服务器就打开开关,输出信息就通过telnet服务器输出到客户端,关闭开关时,这些输出信息就可以不输出,或者输出到另外的地方。不知道哪个朋友有这方面的C#实现的代码,就好像把自定义的服务寄宿到telnet服务里一样。

解决方案 »

  1.   

    /***********************************************************************   Copyright (c) 2010 Alex Zaitsev  All rights reserved.   Simple C# telnet server sample      You can use this code freely for any commercial or non-commercial  purpose. However if you use this code in your program, you should  add the string "Contains code by Alex Zaitsev, www.az3749.narod.ru"  in your copyright notice text. ***********************************************************************/ using System;using System.Net.Sockets;using System.Net;using System.IO;using System.Diagnostics; namespace SimpleTelnetServerSample{     class AsyncRedirect     {         readonly byte[] buf = new byte[4096];         readonly Stream r, w;         readonly AsyncCallback AsyncCallback_;         public AsyncRedirect(Stream Read, Stream Write) { r = Read; w = Write; AsyncCallback_ = this.AsyncCallback; }         void AsyncCallback(IAsyncResult ar)         {             if (!ar.IsCompleted) return;             int n = 0;             try { n = r.EndRead(ar); }             catch (Exception e) {                  Console.WriteLine("EndRead failed:{0}", e);             }             if (n > 0)             {                 w.Write(buf, 0, n);                 w.Flush();                 BeginRead();             }             else             {                 Console.WriteLine("read 0 bytes,finished");                 w.Close();             }         }         public IAsyncResult BeginRead()         {             return r.BeginRead(buf, 0, buf.Length, AsyncCallback_, null);         }         static void Main(string[] args)         {             var psi = new ProcessStartInfo("cmd.exe");             psi.RedirectStandardInput = psi.RedirectStandardOutput = true;             psi.UseShellExecute = false;             var tcpListener = new TcpListener(IPAddress.Any, 23);             tcpListener.Start();             while (true)             {                 var tcpClient = tcpListener.AcceptTcpClient();                 var clientStream = tcpClient.GetStream();                 var p = Process.Start(psi);                 var Pro = new AsyncRedirect(p.StandardOutput.BaseStream, clientStream);                 var Tcp = new AsyncRedirect(clientStream, p.StandardInput.BaseStream);                 Pro.BeginRead();                 Tcp.BeginRead();             }         }     };}