0

我有以下问题:

我的代码应该在 Unity3D (=client) 中的 C# 脚本和本地计算机上的服务器之间建立连接。我的目标是通过统一向服务器发送消息,聊天机器人正在处理消息。之后,他应该将答案发送回统一。问题是聊天机器人服务器正在关闭连接,每次他发送他的答案。这就是为什么客户端每次收到来自服务器的消息时都必须打开它。我首先尝试使用后台线程来解决这个问题,但很快就发现了多线程问题,因为每个更新周期都会打开一个新线程。到目前为止,我还没有找到有效的方法来“更新”线程,这意味着没有创建新线程,但只刷新客户端和服务器之间的连接,或者在每个更新周期后关闭现有线程。

也许有人可以给我一个提示,我可以如何更改我的代码以使其正常工作。提前非常感谢!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class UnityClient2 : MonoBehaviour {     
private TcpClient socketConnection;     
private Thread clientReceiveThread;     
// Use this for initialization  
void Start () {
    ConnectToTcpServer("open");     
}
// Update is called once per frame
void Update () { 
    ConnectToTcpServer("open");         
    if (Input.GetKeyDown(KeyCode.Space)) {             
        SendMessage(); 
        ConnectToTcpServer("close"); 
    }
}   
/// <summary>   
/// Setup socket connection.    
/// </summary>  

private void ConnectToTcpServer (string state) {        
    if (state == "close") {             
        clientReceiveThread.Abort();    
    }       
    else if (state == "open") {
        clientReceiveThread = new Thread (new ThreadStart(ListenForData));          
        clientReceiveThread.IsBackground = true;            
        clientReceiveThread.Start(); 
    }   
    else {
        return;
    } 
}   
/// <summary>   
/// Runs in background clientReceiveThread; Listens for incomming data.     
/// </summary>     
private void ListenForData() {      
    try {           
        socketConnection = new TcpClient("127.0.0.1", 1024);            
        Byte[] bytes = new Byte[1024];             
        while (true) {              
            // Get a stream object for reading              
            using (NetworkStream stream = socketConnection.GetStream()) {                   
                int length;                     
                // Read incomming stream into byte array.                   
                while ((length = stream.Read(bytes, 0, bytes.Length)) != 0) {                       
                    var incommingData = new byte[length];                       
                    Array.Copy(bytes, 0, incommingData, 0, length);                         
                    // Convert byte array to string message.                        
                    string serverMessage = Encoding.ASCII.GetString(incommingData);                         
                    Debug.Log("server message received as: " + serverMessage);                  
                }               
            }           
        }         
    }         
    catch (SocketException socketException) {             
        Debug.Log("Socket exception: " + socketException);         
    }     
}   
/// <summary>   
/// Send message to server using socket connection.     
/// </summary>  
private void SendMessage() {         
    if (socketConnection == null) {             
        return;         
    }       
    try {           
        // Get a stream object for writing.             
        NetworkStream stream = socketConnection.GetStream();            
        if (stream.CanWrite) {           
            //IMPORTANT: Message has to be a null terminated string, so that ChatScript can understand
            string clientMessage ="guest"+ char.MinValue+ ""+ char.MinValue+ ""+char.MinValue;              
            // Convert string message to byte array.                 
            byte[] clientMessageAsByteArray = Encoding.ASCII.GetBytes(clientMessage);               
            // Write byte array to socketConnection stream.                 
            stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length); 
            //                
            Debug.Log("Client sent his message - should be received by server");             
        }         
    }       
    catch (SocketException socketException) {             
        Debug.Log("Socket exception: " + socketException);         
    }     
} 

}`

4

0 回答 0