我在客户端和服务器之间进行异步通信。当客户端从服务器(ReceiveCallback)收到响应时,响应将存储在NetworkHandler类的公共静态字符串响应中。我试图在我的GameHandler类中使用此字段,但它表示响应为空。 我确信NetworkHandler中的缓冲区不是空的,因为我检查了它。
我认为这是因为在响应获取值之前调用了NetworkHandler.response,但我不确定并且我不知道如何解决它...
有关详细说明,请参阅代码中的注释...
请查看此图片以查看GameHandler中的空值:http://i.imgur.com/BPVDlhf.png并在此处查看NetworkHandler中的正确值:http://i.imgur.com/vfY2IuD.png
class NetworkHandler
{
public static string response = String.Empty;
private static void ReceiveCallback(IAsyncResult AR)
{
Socket remote = (Socket)AR.AsyncState;
int received = remote.EndReceive(AR);
byte[] dataBuffer = new byte[received];
Array.Copy(_buffer, dataBuffer, received);
string serverData = Encoding.ASCII.GetString(dataBuffer);
response = serverData;
}
private static void SendCallback(IAsyncResult AR)
{
Socket remote = (Socket)AR.AsyncState;
int sent = remote.EndSend(AR);
remote.BeginReceive(_buffer, 0, _size, SocketFlags.None, new AsyncCallback(ReceiveCallback), remote);
}
public static void sendData(string data)
{
byte[] message = Encoding.ASCII.GetBytes(data);
_client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendCallback), _client);
}
private static void ConnectCallback(IAsyncResult AR)
{
_client = (Socket)AR.AsyncState;
try
{
_client.EndConnect(AR);
_client.BeginReceive(_buffer, 0, _size, SocketFlags.None, new AsyncCallback(ReceiveCallback), _client);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
}
}
}
class GameHandler
{
public void StartGame()
{
// SEND DATA USING BEGINSEND()
SendData("<sg>");
// THIS VALUE IS NULL!!! :(
_response = NetworkHandler.response;
// SO CODE INSIDE IF IS NOT EXECUTED :(
if (_response != null)
{
// If you are the drawer.
if (_response.Substring(0, 5) == "<dra>")
etc.........
}
}
public void SendData(string data)
{
NetworkHandler.sendData(data);
}
}