2013-08-21 96 views
0

我想創建一個機制,在我的服務器遇到只換行後停止讀取輸入。當收到換行時終止套接字連接

下面是代碼(大部分來自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,那麼爲什麼我的支票不工作?

+0

也許檢查'line.Length == 1條&&線[0] ==「\ n'' –

回答

1

由於行是一個字符串,'\ n'是一個字符,它們永遠不會相等。

您應該檢查等於串或字符:

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

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