当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Terminating socket connection when receiving newline

问题描述:

I am trying to create a mechanism where my server stops reading input after it encounters only a newline.

Here is the code (most of it taken from MSDN examples):

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

}

}

But the newline condition is never true and so the server never stops reading input.

I print out the hex characters of what I send and when I connect using netcat:

C:\WINDOWS> nc localhost 55432

Foo<newline>

<newline>

Sure enough, the last line that is sent to the server is:

Bytes read: 1, Content:

, Hex: 0A

I've checked and 0A is hex for \n, so why does my check not work?

网友答案:

As line is a string and '\n' is a char, those are never equal.

You should either check for equal strings or chars:

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

or

if ((line.length > 0 && line[0] == '\n') || (line.length > 1 && line[0] == '\r' && line[1] == '\n'))
分享给朋友:
您可能感兴趣的文章:
随机阅读: