我尝试用异步套接字通信实现我的应用程序。它完美地连接并发送请求但我没有从服务器(Java服务器)接收任何数据。套接字连接
client.BeginConnect(hostname, port,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
new AsyncCallback(ReceiveCallback), client);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
Console.WriteLine(response);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
任何帮助都将不胜感激。
答案 0 :(得分:0)
你的代码几乎没问题,有一个严重的错误。在BeginReceive中,您将客户端套接字实例作为状态对象。在ReceiveCallback函数中,您将其强制转换为StateObject而不是套接字。这将导致在控制台上显示异常。
然而,对于这个错误,将触发ReceiveCallback函数开头的断点。你试过这个吗?无论如何都应该抛出异常。
如果断点未触发,则应独立检查是否确实从服务器发送了某些内容。当然,正如你所说的,所有假设连接都有效。