我正在尝试创建一种机制,使我的服务器在遇到换行符后停止读取输入。
这是代码(大部分来自 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
,那么为什么我的检查不起作用?