C#-TCP客户端未收到服务器响应

时间:2019-01-19 14:12:47

标签: c# unity3d asynchronous tcp

我正在尝试为Unity Game项目创建一个异步TCP客户端。我已经成功创建了TCP套接字连接,但是我无法正确接收任何服务器响应。

这是我的TCP客户端侦听器代码:

<languaje>
    <xsl:value-of select="Book/languaje"/>
</languaje>

这是我启动客户端的方式:

<previous>

当服务器将数据发送到Unity 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);
}

以下允许我在统一线程中执行被调用的函数。

Debug.Log("RECEIVING");

您知道为什么我的异步TCP客户端无法正常工作吗?

0 个答案:

没有答案