从套接字读取直到客户端在C#中发送EOL

时间:2009-03-24 22:44:21

标签: c# sockets

我有一个基本的套接字服务器,如下所示:

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

现在我希望它接受输入,直到用户(telnet当前)发送EOL(按回车),上面的代码大部分是我到目前为止尝试过的,我应该怎么做?

2 个答案:

答案 0 :(得分:1)

嗯,TCP在流中工作,所以为了检测任何东西,你将不得不预见到\ r \ n不是缓冲区中唯一的东西。

替换

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

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

不要忘记用来自TCPStream的数据重新填充'bit'...意思是

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

你需要

    client.Receive(buffer);

所以它看起来像:

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

并且......异常处理程序会在客户端断开连接时通知您。

答案 1 :(得分:0)

在发送EOL字符时,您可能会获得多个字符:

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