Я пытаюсь создать асинхронный TCP-клиент для проекта Unity Game.Я успешно создаю соединение через сокет TCP, но не могу правильно получить ответ от сервера.
Вот мой код прослушивателя TCP-клиента:
#region TCP Client
public static string ServerIP = "127.0.0.1";
public static int TCPPort = 8080;
private IPEndPoint serverTCPEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), TCPPort);
public static Socket TCPClient;
public Thread SocketThread;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private void StartTCPClient()
{
// Connect to a remote device.
try
{
// Create a TCP/IP socket.
TCPClient = new Socket(serverTCPEndPoint.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
TCPClient.BeginConnect(serverTCPEndPoint,
new AsyncCallback(ConnectCallback), TCPClient);
connectDone.WaitOne();
// Receive the response from the remote device.
TCPReceive();
receiveDone.WaitOne();
// Write the response to the console.
Debug.Log("Response received: " + response);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Complete the connection.
TCPClient.EndConnect(ar);
Debug.Log("Socket connected to: " + TCPClient.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
private void TCPReceive()
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = TCPClient;
// Begin receiving the data from the remote device.
TCPClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
Debug.Log("RECEIVING");
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
// Read data from the remote device.
int bytesRead = TCPClient.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
TCPClient.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();
Debug.Log("RECEIVING 2: " + response);
UnityThread.executeInUpdate(() =>
{
OnIncomingTCPData(response);
});
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
#endregion
Вот как я запускаю клиент:
// Use this for initialization
void Start()
{
int accId = ClientLoginServer.accountId;
DuloGames.UI.Demo_Chat.worldServer = this;
if (accId != 0)
{
CursorMode cursorMode = CursorMode.Auto;
Vector2 hotSpot = Vector2.zero;
SocketThread = new Thread(StartTCPClient);
SocketThread.IsBackground = true;
SocketThread.Start();
Cursor.SetCursor(brownCursor, hotSpot, cursorMode);
//GameObject go = Instantiate(CharacterNamePrefab) as GameObject;
GameObject CharacterSelectPanel = GameObject.Find("/Canvas/Panel/CharacterSelectPanel");
}
DontDestroyOnLoad(worldserverConnection);
}
Все, что я вижу, когда сервер отправляет данные в прослушиватель клиента Unity TCP, - это следующая строка:
Debug.Log("RECEIVING");
Однако эта строка, кажется, недоступна:
Debug.Log("RECEIVING 2: " + response);
Следующее позволяет мне выполнять вызываемые функции в главном потоке единицы.
UnityThread.executeInUpdate(() =>
{
OnIncomingTCPData(response);
});
Есть ли у вас какие-либо идеи, почему мой асинхронный TCP-клиент работает неправильно?