tags:

views:

423

answers:

2

I have a basic socket server that looks like this:

    IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);
    Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        newsock.Bind(localEndPoint);
    }
    catch (Exception e)
    {
        //Errors handled
    }
    newsock.Listen(10);
    Console.WriteLine("Bound to port 8000");
    Socket client = newsock.Accept();
    while (client.Connected)
    {
        Console.WriteLine("Connection recieved.");
        string outputString = null;
        byte[] buffer = new byte[4];
        client.Receive(buffer);
        string bit = null;
        while (bit != "\r\n" || bit != "\n" || bit != "\r")
        {
            bit = Encoding.ASCII.GetString(buffer);
            outputString += bit;
        }
        Console.WriteLine(outputString);
    }

Right now I want it to accept input until the user (telnet currently) sends an EOL (presses enter) the code above is mostly what I've tried thus far, how should I be doing this?

A: 

You are probably getting more than one character when the EOL character is sent try:

while (bit != null && !bit.EndsWith("\r") && !bit.EndsWith("\n") )
sipwiz
+1  A: 

Well, TCP works in streams, so in order to detect anything, you are going to have to anticipate the case that a \r\n is not the only thing that is in your buffer.

Replace

bit != "\r\n" || bit != "\n" || bit != "\r"

with

!bit.Contains("\r") && !bit.Contains("\n")

Don't forget to repopulate 'bit' with data from the TCPStream... meaning in

    while (bit != "\r\n" || bit != "\n" || bit != "\r")
    {
        bit = Encoding.ASCII.GetString(buffer);
        outputString += bit;
    }

you need

    client.Receive(buffer);

so it looks like:

    while (bit != "\r\n" || bit != "\n" || bit != "\r")
    {
        bit = Encoding.ASCII.GetString(buffer);
        outputString += bit;
        client.Receive(buffer);
    }

And... an exception handler will let you know when the client disconnects.

Lomilar
Some of what you mentioned was taken care of and just not posted. But this worked just as expected.
Unkwntech