次のクラスがあります(ネット上の例から取得しました。変更したのは、ドメイン名の代わりにIPアドレスとポートを使用することだけです):
public class ConnectionManager
{
private static ManualResetEvent allDone = new ManualResetEvent(false);
private string message = "foobar";
public Action MessageSent;
public Action<string> MessageReceived;
public void SendMessage()
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.1.91.48:3330/");
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
MessageSent();
// Keep the main thread from continuing while the asynchronous
// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(message);
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
allDone.Set();
MessageReceived(responseString);
}
}
上記のコードはメッセージの送信に失敗します。ステップすると、GetRequestStreamCallback 内にいるときに IAsyncResult 内に次のエラーが表示されます。
AsyncWaitHandle = 'asynchronousResult.AsyncWaitHandle' がタイプ 'System.NotSupportedException' の例外をスローしました
私は何を間違っていますか?このコードを修正するにはどうすればよいですか?