簡體   English   中英

通過服務器端使用 te.net 查找特定字符串 C# 控制台

[英]To find a particular string using telnet through a server side C# Console

我編寫了這段代碼來檢查文件中的特定字符串。 現在它檢查字符串。 但是我怎樣才能把“它存在”的回復發回給客戶呢? 服務器端程序應具有所有代碼。 它還接受多個客戶端。

本程序的流程如下

基本上,如果客戶想要檢查文件中是否有特定的字符串(單詞),他會通過 te.net 上的端口連接此代碼。 他輸入他想要搜索的字符串(在 te.net 上)並將其發送到服務器端。 這個服務器端程序從文件中為他檢查。 如果它存在,它會向客戶端發回一條消息,說“該字符串存在於文件中”,如果不存在,它應該發送一條消息說“它不存在”。

搜索字符串(“hello”)在此程序中。 我怎樣才能讓客戶端從客戶端(te.net)搜索它? 這是我得到很多幫助和教程的地方。 有人可以幫幫我嗎?

編輯 - 我已經更改了代碼,以便它向客戶端發送回復。 我現在需要知道的是,如何讓客戶端通過客戶端(te.net)進行搜索(輸入他想搜索的詞)? 任何幫助將不勝感激。 我也更新了我的代碼。

謝謝你。

class Program
{
    static void Main(string[] args)
    {
        IPAddress ipad = IPAddress.Parse("127.0.0.1");
        TcpListener serversocket = new TcpListener(ipad, 8888);
        TcpClient clientsocket = default(TcpClient);
        Byte[] bytes = new Byte[256];
        serversocket.Start();

        Console.WriteLine(">> Server Started");
        while(true)
        {
            clientsocket = serversocket.AcceptTcpClient();
            Console.WriteLine("Accepted Connection From Client");

            LineMatcher lm = new LineMatcher(clientsocket);
            Thread thread = new Thread(new ThreadStart(lm.Run));
            thread.Start();
            Console.WriteLine("Client connected");
        }

        Console.WriteLine(" >> exit");
        Console.ReadLine();
        clientsocket.Close();
        serversocket.Stop();
    }
}

public class LineMatcher
{
    public string fileName = "c:/myfile2.txt";
    private TcpClient _client;

    public LineMatcher(TcpClient client)
    {
        _client = client;
    }

    public void Run()
{
    byte[] data = new byte[256];
    NetworkStream strm = _client.GetStream();
    try
    {
        using (var r = new StreamReader("c:/myfile2.txt"))
        {

            string line = "";
            bool done = false;

            int lineNumber = 0;
            String s = r.ReadToEnd();

            ASCIIEncoding encoder = new ASCIIEncoding();
            while (String.IsNullOrEmpty(s))
            {
                data = encoder.GetBytes("There is no data in the file.");
                Console.WriteLine("There is no data in the file.");
            }
            if (s.IndexOf("hello", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                data = encoder.GetBytes("It is Present.");

            }
            else
            {
                data = encoder.GetBytes("It is not Present");
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.ToString());
    }

    strm.Write(data, 0, data.Length);
    strm.Flush();
    Console.WriteLine("Closing client");
    _client.Close();
}

}

而不是if (s==null) ,你應該檢查字符串是否包含這個詞。 非常有創意,我們可以像這樣檢查單詞“word”: if (s.IndexOf("word") >= 0)它在s中搜索“word”的位置並返回索引。 在 C# 中,索引始終從 0 開始。如果字符串“word”不包含在您的文件字符串中,它將返回 -1。 因此,如果包含單詞, if語句將返回true ,否則返回false

if視為僅采用一個參數的語句。 該參數要么是true要么是false (s==null)是一個表達式,它返回值truefalse ,然后由 if 語句使用。

但是,這將不起作用,例如,如果文件顯示為: THIS IS A WORD ,因為“word”不等於“WORD”。 您可以通過使用不區分大小寫的比較來解決這個問題,如下所示:

if(s.IndexOf("word", StringComparison.CurrentCultureIgnoreCase) >= 0) {
  // contains "word"
} else {
  // does not contain "word"
}

看看下面的內容以供參考

您的客戶端應用程序將只能搜索一次。 這是因為在執行搜索后,您關閉了連接。

Console.WriteLine("Closing client");
_client.Close();

如果您希望連接保持打開狀態,您需要包含一個循環以確保您返回到LineMatcher class 的開頭以重新搜索。

我沒有檢查這個字符串的IndexOf ,而是簡單地使用了Contains方法。 IndexOf旨在查找 substring 在字符串中的位置,而Contains是為特定目的而構建的,即簡單地檢查 substring 是否存在。 請注意,這區分大小寫。

else if (s.Contains("HTTP"))
{

我強烈建議您首先讓搜索應用程序作為一個獨立的應用程序運行,然后編寫一個 te.net 服務器來啟動您的原始應用程序。 這是兩個獨立的函數,您會發現單獨測試它們要容易得多。

我解決了。 :) 我就是這樣做的。 有什么改進建議嗎?

namespace ServerSideApplication
{
    class Program
    {
     static void Main(string[] args)
      {
        TcpListener socketListener = new TcpListener(8888);
        TcpClient netClient = default(TcpClient);
        StreamReader sr;
        StringBuilder sb = new StringBuilder();

        socketListener.Start();
        sr = new StreamReader("c:\\test.txt");
        sb.Append(sr.ReadToEnd());
        while (true)
        {
            netClient = socketListener.AcceptTcpClient();
            Console.WriteLine("Accepted Connection From Client" + Environment.NewLine + "Client connected");
            ServerSide ss = new ServerSide();
            ss.startServerSide(netClient, sb);
        }
        socketListener.Stop();
    }
}

class ServerSide
{

    TcpClient netClient;
    StringBuilder sb;

    public void startServerSide(TcpClient netClient, StringBuilder sb)
    {
        this.netClient = netClient;
        this.sb = sb;
        Thread thread = new Thread(processRequest);
        thread.Start();
    }
    private void processRequest()
    {
        byte[] data = new byte[4096];
        int bytesRead;
        NetworkStream strm = netClient.GetStream();
        bytesRead = 0;
            try
            {

                NetworkStream ns = netClient.GetStream();

                string clientChar = "", s = "";
                do
                {
                    bytesRead = ns.Read(data, 0, (int)data.Length);
                    clientChar = Encoding.ASCII.GetString(data).Replace("\0", "");
                    s += clientChar;
                } while (clientChar != Environment.NewLine);

                s = s.Trim();

                ASCIIEncoding encoder = new ASCIIEncoding();

                if (String.IsNullOrEmpty(s))
                {
                    data = encoder.GetBytes("There is no data in the file.");
                    Console.WriteLine("There is no data in the file.");
                }

                if (sb.ToString().Contains(s))
                {
                    data = encoder.GetBytes("It Is Present In The File.");
                }
                else
                {
                    data = encoder.GetBytes("It Is Not Present In The File.");
                }
                strm.Write(data, 0, data.Length);
                strm.Flush();
                Console.WriteLine("Closing client");
                netClient.Close();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
            }
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM