私は最近、Java Webアプリケーションが別のサーバー上に存在するレガシーVB6アプリケーションと通信するための努力の一環として、C#で素早く汚れた概念証明プロキシサーバーを作成しました。C#の非同期ネットワークコードのパターンはよく知られていますか?
プロキシサーバーとクライアントはどちらも同じメッセージ形式を使用します。コードに私は、サーバーによって生成され、クライアントと応答の両方からの要求を表現するためにProxyMessage
クラスを使用します。
public class ProxyMessage
{
int Length; // message length (not including the length bytes themselves)
string Body; // an XML string containing a request/response
// writes this message instance in the proper network format to stream
// (helper for response messages)
WriteToStream(Stream stream) { ... }
}
メッセージは以下のようになりほど単純です:ボディ+メッセージ本体の長さ。
クライアントへの接続を表す別のProxyClient
クラスがあります。これは、プロキシと単一のクライアント間のすべての対話を処理します。
私は、非同期ソケットプログラミングに関連するボイラープレートコードを簡略化するためのデザインパターンまたはベストプラクティスであると思いますか?たとえば、誤ってバイトを失うことがないように、現在のメッセージの処理にどのくらいの距離があるかを把握する必要があるように、読み込みバッファを管理するために注意する必要があります。現在のコードでは、TcpClient.BeginRead
のコールバック関数でこの作業をすべて行い、いくつかのインスタンス変数を使用してバッファの状態と現在のメッセージ処理状態を管理しています。
BeginRead
に渡す私のコールバック関数のコードは、コンテキストの関連するインスタンス変数と共に以下のとおりです。コードは "そのまま"うまく動作しているようですが、それを明確にするためにリファクタリングできるかどうかは疑問です。
private enum BufferStates
{
GetMessageLength,
GetMessageBody
}
// The read buffer. Initially 4 bytes because we are initially
// waiting to receive the message length (a 32-bit int) from the client
// on first connecting. By constraining the buffer length to exactly 4 bytes,
// we make the buffer management a bit simpler, because
// we don't have to worry about cases where the buffer might contain
// the message length plus a few bytes of the message body.
// Additional bytes will simply be buffered by the OS until we request them.
byte[] _buffer = new byte[4];
// A count of how many bytes read so far in a particular BufferState.
int _totalBytesRead = 0;
// The state of the our buffer processing. Initially, we want
// to read in the message length, as it's the first thing
// a client will send
BufferStates _bufferState = BufferStates.GetMessageLength;
// ...ADDITIONAL CODE OMITTED FOR BREVITY...
// This is called every time we receive data from
// the client.
private void ReadCallback(IAsyncResult ar)
{
try
{
int bytesRead = _tcpClient.GetStream().EndRead(ar);
if (bytesRead == 0)
{
// No more data/socket was closed.
this.Dispose();
return;
}
// The state passed to BeginRead is used to hold a ProxyMessage
// instance that we use to build to up the message
// as it arrives.
ProxyMessage message = (ProxyMessage)ar.AsyncState;
if(message == null)
message = new ProxyMessage();
switch (_bufferState)
{
case BufferStates.GetMessageLength:
_totalBytesRead += bytesRead;
// if we have the message length (a 32-bit int)
// read it in from the buffer, grow the buffer
// to fit the incoming message, and change
// state so that the next read will start appending
// bytes to the message body
if (_totalBytesRead == 4)
{
int length = BitConverter.ToInt32(_buffer, 0);
message.Length = length;
_totalBytesRead = 0;
_buffer = new byte[message.Length];
_bufferState = BufferStates.GetMessageBody;
}
break;
case BufferStates.GetMessageBody:
string bodySegment = Encoding.ASCII.GetString(_buffer, _totalBytesRead, bytesRead);
_totalBytesRead += bytesRead;
message.Body += bodySegment;
if (_totalBytesRead >= message.Length)
{
// Got a complete message.
// Notify anyone interested.
// Pass a response ProxyMessage object to
// with the event so that receivers of OnReceiveMessage
// can send a response back to the client after processing
// the request.
ProxyMessage response = new ProxyMessage();
OnReceiveMessage(this, new ProxyMessageEventArgs(message, response));
// Send the response to the client
response.WriteToStream(_tcpClient.GetStream());
// Re-initialize our state so that we're
// ready to receive additional requests...
message = new ProxyMessage();
_totalBytesRead = 0;
_buffer = new byte[4]; //message length is 32-bit int (4 bytes)
_bufferState = BufferStates.GetMessageLength;
}
break;
}
// Wait for more data...
_tcpClient.GetStream().BeginRead(_buffer, 0, _buffer.Length, this.ReadCallback, message);
}
catch
{
// do nothing
}
}
これまでのところ、私の唯一の本当の考えは別のMessageBuffer
クラスにバッファに関連するものを抽出し、単に彼らが到着すると、私の読み込みコールバックがそれに新しいバイトを追加することです。 MessageBuffer
は、現在のBufferState
のようなものを心配し、完全なメッセージを受信したときにイベントを発生させます。ProxyClient
は、リクエストを処理できるメインのプロキシサーバーコードにさらに伝播する可能性があります。
あなたはこれを利用できるように開発したもののオープンソース版を持っていないでしょうか? – Maslow