-1

I have written this code to check for a particular string from a file. Right now it checks for the string. But how can I send the reply back saying "it is present" to the client? The server side program should have all the codes. It also accepts multiple clients.

The Procedure of this program is as follows

Basically if a client wants to check if there's a particular string(word) in a file, he connects this code through a port on telnet. He types in the strings he wants to search(on telnet) and send it to the server side. And this server side program checks it for him from the file. And if it is present, it sends a message back to the client saying "The string is present in the file" And if it isn't, It should send a message saying "It is not".

The search string("hello") is in this program. How can I enable the client to search for it from client side(telnet)? This is where I've come till with a lot of help and tutorials. Can someone please help me?

EDITED - I have changed the code such that it sends a reply back to the client. All I need to know now is, how can I enable the client to search (type the word he wants to search for) through the client side(telnet)? Any help will be really appreciated. I have updated my code too.

Thank you.

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();
}

}

3692
  • 628
  • 2
  • 6
  • 17

3 Answers3

1

Instead of if (s==null), you should check if the string contains the word. Being very creative, we can check for the word "word" like so: if (s.IndexOf("word") >= 0) which searches for the location of "word" within s and returns the index. In C#, indexes always start at 0. If the string "word" is not contained within your file string, it will return -1. Therefore that if statement will return true if the word is contained, or false if it is not.

Think of if as a statement which takes only one parameter. And that parameter is either true or false. The (s==null) is an expression which returns the value true or false which is then used by the if statement.

However, this will not work, if for instance, the file reads: THIS IS A WORD, because "word" does not equal "WORD". You can get around this by using a case insensitive compare like so:

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

Have a look at the following for reference

Vincent McNabb
  • 33,327
  • 7
  • 31
  • 53
  • Thank you so much. :) I tried your code, but it gives the following error.. The name 'StringComparisonCurrentCultureIgnoreCase' does not exist in the current context. – 3692 Apr 10 '12 at 11:33
  • Moreover, I don't want to give the search word in the program. The client should be able to give the word from the telnet. How can I do that? – 3692 Apr 10 '12 at 11:36
  • @3692 I was missing a `.` in between StringComparison and CurrentCultureIgnoreCase. Try it again. It is a console application, so the parameters typed in from the console are put into the `args[]` variable in main. Just pass that value through to your Run function. See this question for how to do that http://stackoverflow.com/questions/1195896/c-sharp-threadstart-with-parameters – Vincent McNabb Apr 10 '12 at 11:38
  • Lol found that out. :) This is how it was when I first wrote my program. But I want the client to be able to give as many strings he wants to search for from the file. Right now it loses connection as soon as it searches for the word. How can I do that mate? – 3692 Apr 10 '12 at 11:44
  • I have changed the code. But how do i send the data to client(Telnet)? – 3692 Apr 16 '12 at 04:33
1

Your client applications will only be able to search once. This is because after you perform the search, you close the connection.

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

If you want the connection to stay open you will need to include a loop to ensure you return to the beginning of the LineMatcher class to re-search.

Rather than checking the IndexOf this string, I'd instead simply use the Contains method. While IndexOf is designed to find where a substring is located within a string, Contains is built for the specific purpose of simply checking whether or not a substring exists. Note that this is not case insensitive.

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

I would strongly recommend you get the searching application working first, as a stand-alone application, and then write a telnet server which launches your original application. These are two separate functions, and you'll find it a lot easier to test them individually.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
  • Broadhurt Thank u so much. Will correct the first two parts of what u told. But how do I do the latter part? Could u help me with it please? – 3692 Apr 16 '12 at 06:03
  • This should do it. Test it in a Console app until you are happy, then re-run as a telnet server. `static void Main(string[] args) { LineMatcher lm = new LineMatcher(clientsocket); Thread thread = new Thread(new ThreadStart(lm.Run)); thread.Start(); }` – Kirk Broadhurst Apr 16 '12 at 06:24
  • Could you just tell me how could include a loop to keep the clients open? – 3692 Apr 18 '12 at 07:08
1

I solved it. :) This is how I did it. Any suggestions on improving it?

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());
            }
    }
}

}

3692
  • 628
  • 2
  • 6
  • 17