UnkwnTech
UnkwnTech

Reputation: 90871

Reading from socket until client sends EOL in C#

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?

Upvotes: 0

Views: 6095

Answers (2)

Lomilar
Lomilar

Reputation: 531

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.

Upvotes: 1

sipsorcery
sipsorcery

Reputation: 30699

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

while (bit != null && !bit.EndsWith("\r") && !bit.EndsWith("\n") )

Upvotes: 0

Related Questions