【发布时间】:2015-06-14 09:03:09
【问题描述】:
我尝试使用异步套接字通信来实现我的应用程序。它完美地连接并发送了请求,但我没有从服务器(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());
}
}
任何帮助将不胜感激。
【问题讨论】:
-
好吧,
ConnectCallback不见了——还有:你怎么知道你已经连接了?您是否调试过此代码(在ReceiveCallback中设置断点?) - 您是否尝试通过telnet 连接?当然,如果您开始接收并且那里还没有数据,您可能会看到0字节并停止一切 -
已连接 = true;此属性在调试模式下可见。我在receivecallback方法中设置了断点,但它没有执行。它一直在调试,直到beginreceive之后它从调试模式结束。而且我没有尝试过 telnet。
-
你也可以考虑检查一下stackoverflow.com/a/1388691/1537726