接收换行符时终止套接字连接

时间:2013-08-21 21:56:24

标签: c# .net sockets network-programming

我正在尝试创建一种机制,让我的服务器在遇到只有换行符后停止读取输入。

以下是代码(大部分内容来自MSDN示例):

private void ReadRequest(IAsyncResult ar)
{
    SocketState state = (SocketState) ar.AsyncState;
    Socket handler = state.workSocket;

    try
    {
        int read = handler.EndReceive(ar);
        if (read > 0)
        {
            string line = Encoding.ASCII.GetString(state.buffer, 0, read);
            byte[] temp = Encoding.ASCII.GetBytes(line);
            string hex = BitConverter.ToString(temp);
            eventLog.WriteEntry(string.Format("Bytes read: {0}, Content: {1}, Hex: {2}", line.Length, line, hex));
            if (line.Equals(Environment.NewLine) || line.Equals('\n'))
            {
                eventLog.WriteEntry("Double line break.");
                string response = HandleRequest(state.sb.ToString());
                handler.BeginSend(Encoding.ASCII.GetBytes(response), 0, response.Length, SocketFlags.None, new AsyncCallback(SendDone), state);
                return;
            }

            state.sb.Append(line);
            handler.BeginReceive(state.buffer, 0, SocketState.BufferSize, SocketFlags.None, new AsyncCallback(ReadRequest), state);
        }
        else
        {
            string response = HandleRequest(state.sb.ToString());
            eventLog.WriteEntry(response, EventLogEntryType.Information);
            handler.BeginSend(Encoding.ASCII.GetBytes(response), 0, response.Length, SocketFlags.None, new AsyncCallback(SendDone), state);
        }
    }
    catch (Exception exception)
    {
        eventLog.WriteEntry(string.Format("Error occured while reading the request: {0}", exception.Message), EventLogEntryType.Error);
    }
}

但换行条件永远不会成立,因此服务器永远不会停止读取输入。

我打印出我发送的十六进制字符以及使用netcat连接的时候:

C:\WINDOWS> nc localhost 55432
Foo<newline>
<newline>

果然,发送到服务器的最后一行是:

Bytes read: 1, Content: 
, Hex: 0A

我已检查0A\n的十六进制,为什么我的检查不起作用?

1 个答案:

答案 0 :(得分:1)

由于line是一个字符串而'\ n'是一个char,所以它们永远不会相等。

您应该检查相等的字符串或字符:

if (line.Equals(Environment.NewLine) || line == "\n")

if ((line.length > 0 && line[0] == '\n') || (line.length > 1 && line[0] == '\r' && line[1] == '\n'))
相关问题