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

本文关键字:终止 套接字 连接 换行符 | 更新日期: 2023-09-27 18:28:28

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

以下是代码(大部分来自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的十六进制,那么为什么我的检查不起作用呢?

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

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

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

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

if ((line.length > 0 && line[0] == ''n') || (line.length > 1 && line[0] == ''r' && line[1] == ''n'))