0

This is a program to search for strings from a file. The string required by the client is given from the client side, in my case, using telnet. The program I have written is a server side one. It accepts multiple clients. But, the problems I am unable rectify are-

  • It doesn't check for strings from the file.
  • As soon as the client gets connected, the client cannot type in the strings they want to search in that particular file.
  • It doesn't send the reply back (i.e. If the string is present in the file or not) to the client. Its only shown on the server side.

How do I proceed further? Could someone tell me where am I going wrong? Could someone please help me out with the code? This is my try at the program..

class Program
{

    static void Main(string[] args)
    {
        IPAddress ipad = IPAddress.Parse("192.168.0.181");
        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 //I've jumbled it up here. Don't know what exactly to do..
{
     public string fileName = "c:/myfile2.txt";
     private TcpClient _client;

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

     public void Run()
     {
         try
         {
              StreamReader sr = new StreamReader("c:/myfile2.txt");
              using (var reader = new StreamReader(_client.GetStream()))
              {
                  string line ="";
                  int lineNumber = 0;
                  while (null != (line = sr.ReadLine()))
                         {
                             lineNumber += 1;
                             byte[] data = new byte[1024];
                             NetworkStream stream = _client.GetStream();
                             //if (line.Equals(line))
                             for (int ct = stream.Read(data,0, data.Length-1); 0 < ct; ct = stream.Read(data,0,data.Length-1))

                                 line += Encoding.ASCII.GetString(data, 0, ct);
                             line = line.Trim();

                             {
                                 lineNumber.ToString();

                                 data = Encoding.ASCII.GetBytes(line);
                                 _client.Client.Send(data, data.Length, SocketFlags.None);
                                 Console.WriteLine("Line {0} matches {1}", lineNumber, line);
                             }
                         }
             }
         }
         catch (Exception ex)
         {
             Console.Error.WriteLine(ex.ToString());
         }
         Console.WriteLine("Closing client");
         _client.Close();
     }
 }
3692
  • 628
  • 2
  • 6
  • 17
  • from this code we cannot possible see what's going on - you should first try to debug your code to identify the places that go run (is the lm.Run entered) and of course we need to see the code in `LineMatcher.Run` as this might be the cruical point – Random Dev Apr 05 '12 at 06:25
  • @CarstenKönig Thank u so much Carsten. But I didnt get u. Its just been a month since i started learning about C#. Could u please tell me how do i do it? And LineMatcher.Run? How? – 3692 Apr 05 '12 at 06:34
  • You don't know how to set a breakpoint and debug the code? - Just set a breakpoint (F9) where you call `thread.Start()` and anotherone inside the `Run` method in your `LineMatcher` class - then start your program (F5) and use telnet to connect and see if your breakpoints are hit and what your programm is doing from there ... and `LineMatcher.Run` is the name of the method `Run` where the *magic* happens (you did write it - didn't you?) – Random Dev Apr 05 '12 at 06:39
  • BTW: 3 favs. and 2 upvotes on this? - wow, did you get your friends to increase your rep? – Random Dev Apr 05 '12 at 06:40
  • @CarstenKönig I absolutely know no one here on SO. Yes I did write it looking through a lot of tutorials. And thank you for the procedure, I will follow everything you asked me to and see whats going wrong. :) Still a novice Cartsen. Sorry about that. Interested to learn a lot. And i'm happy to say, i am.. :) – 3692 Apr 05 '12 at 06:50
  • No offense but you should really take care to include the parts that matters - and that's the code where you "process" the client - please just add this and we might be able to assist you – Random Dev Apr 05 '12 at 07:00
  • I did follow what you said. When it hits the break point at `thread.Start`, the program doesn't proceed further. – 3692 Apr 05 '12 at 07:06
  • ok - good think: you can connect to your program. The program won't continue unless you tell it so (for example F5 again - look into the Debug-Menu!) - but you can remove this breakpoint now, it was just to check if you hit this code (could have used the Console.WriteLine-"debugger" too ;) - no make sure to have the second breakpoint in your Thread-method (Run) and repeat - look what your code is doing there by stepping through it (remember Debug-Menu) ... and consider reading some tutorials/books on how to use IDEs, Debuggers, etc. - this is extremly basic tooling stuff! – Random Dev Apr 05 '12 at 08:28
  • @CarstenKönig - Ok Cartsen, i did that. But the program still refuses to continue even after taking out the breakpoint from `thread.start`. I just had the break point on thread method Run i.e. `public void Run`. Still its not doing anything. It stops wherever it used to when there was a break point on `thread.start`. What do i do next? – 3692 Apr 05 '12 at 09:38
  • @CarstenKönig - Ok to receive the message from the client, i added this in between the code. Its not working. Have I gone wrong in writing the code again? This is where i added it. `byte[] data = new byte[1024]; NetworkStream stream = _client.GetStream(); for (int ct = stream.Read(data,0, data.Length-1); 0 < ct; ct = stream.Read(data,0,data.Length-1)) line += Encoding.ASCII.GetString(data, 0, ct); line = line.Trim();` This is what i added in `while(null---) { The above code }` Is it wrong? – 3692 Apr 05 '12 at 09:42
  • does the debugger hit the code there? It's a bit of a mess but I still don't know where your code stops (do you see your messages in the Console?) – Random Dev Apr 05 '12 at 10:56
  • @CarstenKönig The debugger hits the code till here --> `for (int ct = stream.Read(data,0, data.Length-1); 0 < ct; ct = stream.Read(data,0,data.Length-1))` The values(strings) I pass from the client side(telnet) is not shown on the server side.. But while debugging it every line in the program, the values appear (if this was what you were referring to as "messages in the console"). I am confused and I suppose I am confusing you bigtime too. Sorry Carsten. :) – 3692 Apr 05 '12 at 11:03
  • @CarstenKönig Nevertheless, I really appreciate your patience and help.. Thanks a ton.. :) – 3692 Apr 05 '12 at 11:09
  • @3692 - If you have code to ask about, please update the question, I can't work off comments. Furthermore why are you using 127.0.0.1 thats the local loopback address. – Security Hound Apr 05 '12 at 11:12
  • @Ramhound I have updated the question.. I just used that address for temporary basis.. – 3692 Apr 05 '12 at 11:23
  • well only saw it right now - don't you want to read the bytes from the file? - you should read it from `sr` instead of `stream` then - it's getting long here so I will try to put this into an answer – Random Dev Apr 05 '12 at 13:05

1 Answers1

1

I think you got some pieces in your Run-method swapped - here is a version that should do the job:

public void Run()
{
     byte[] data;
     try
     {
        using (var r = new StreamReader("c:/myfile2.txt"))
        {
            string line ="";
            int lineNumber = 0;
            while (null != (line = r.ReadLine()))
            {
                data = Encoding.ASCII.GetBytes(line + "\n");
                _client.Client.Send(data, data.Length, SocketFlags.None);
            }
        }
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine(ex.ToString());
     }
     Console.WriteLine("Closing client");
     _client.Close();
}

Please note that I'm not 100% sure what you are trying to do (I think you want your textfile send line-by-line to your Terminal) - so you might have to change some bits here and there.

Don't know where the Stream-messes in your code came from but I guess you tried various tutorials/snippets and forgot to clean up ;)

Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • Haha.Your right:) Your program works absolutely fine. But what I'm actually trying to do is- Suppose there's a client,who wants to search for strings from the file(he just wants to check if the word is present in the file or not),he just types in the string (in telnet).The server side program(which you have been helping me throughout) should search for the string and if it is present in the file,it should send a message to the client that "yes the {string} is present" or it should say "no it isnt".The client should be able to send the string he wants to search for to the server. – 3692 Apr 06 '12 at 04:36
  • Ok this will be indeed some more work (basically you have to say: here comes x bytes and then send the bytes for the query string first - on the serverside receive the 4(for example) bytes for the query-strings length and then the remaining querystring-bytes, etc. - after all if it gets this complicated you should consider using WCF or something similar which makes those low-level communications for you – Random Dev Apr 06 '12 at 11:32
  • Good Mornin! Yeah you got that right. But I was asked to just use the c# console application and code it. Is it gonna be hard to do it in c#? – 3692 Apr 06 '12 at 11:53
  • No WCF is rather simple and you can host those services in a C# console application – Random Dev Apr 06 '12 at 12:24
  • Tried doing it in WCF.. I was asked not use it. Back to c# console application again. How do I do it? :( – 3692 Apr 09 '12 at 06:23
  • You've got everything you need already - please try to do it on your own, and if you cannot please open a new question detailing what you tried and where you fail. – Random Dev Apr 09 '12 at 16:21
  • I Solved it. :) Just have a look at it if its right. Here's the link. :) http://stackoverflow.com/questions/10086689/to-find-a-particular-string-using-telnet-through-a-server-side-c-sharp-console – 3692 Apr 18 '12 at 07:46