Updating Threads in C#/Unity3D for TCP/IP Client Server Connection

1k Views Asked by At

I have the following problem:

My code should establish a connection between a C#-script in Unity3D (=client) and a server on a local machine. My goal is to send messages over unity to the server, where a chatbot is processing the message. After that he should send an answer back to unity. The problem is that the chatbot-server is closing the connection, everytime he has sended his answer. Thats why the client has to open it everytime he received the message from the server. I first tried to solve this with a background thread, but quickly stumbled over the multi-thread problem, as a new thread is opened every update cycle. Up until now i have found no effective way to either just "update" the thread, meaning that no new thread is created, but only the connection between client and server is refreshed, or to just close the existing thread after each update cycle.

Maybe someone could give me a hint, how i could change my code to work properly. Thanks a lot in advance!

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);         
    }     
} 

}`

0

There are 0 best solutions below