private void Receive(object clientSocket) { Socket s = (Socket)clientSocket; MessageParser mp = new MessageParser(); RMessage m; SMessage sMsg; SMessage errorMsg; Exception error; while (true) { try { m = null; sMsg = null; errorMsg = null; error = null; m = mp.Parse(s); try { sMsg = OnMessageArrived(m); } catch (Exception e) { error = e; } // 如果 在 OnMessageArrived 中没有读取完 m.Content ,则需要继续读完 , // 否则没有读完的内容会被当成下一次 Request 的 Head , 导致请求错误 。 if (m.Content != null) { mp.ReadToEnd(m.Content); } if (error != null) { errorMsg = new SMessage(); errorMsg.Error = error.Message; mp.Send(ref s, errorMsg, null); } else { mp.Send(ref s, sMsg, null); } } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + ex.ToString()); s.Shutdown(SocketShutdown.Both); s.Close(); break; } } }