C# TCP Server being able to manually kill it with a boolean

I’m developing a Unity App which requires a TCP server. I’m a C# Newbie and when I implemented the TCP Server I used the following code which is modified from something that I found online.

I start the TCP Server by calling this function:

    public static bool StartServer(int port, ITcpServer serverComm){

       serverSocket = new TcpListener(IPAddress.Any,port);
       keepServerAlive = true;
        
       RxBuffer = new byte[1024];
        
       comm = serverComm; // Just an interface for notifying of data received. 

       try {
           serverSocketThread = new Thread( new ThreadStart(OnClientDataReceived) );
           serverSocketThread.IsBackground = true;
           serverSocket.Start();
           serverSocketThread.Start();         
        }
        catch (Exception e){
            VMLog.error("Failed to start TCP Server. Reason: " + e.Message); // Basically the same same thing as Debug.Log for this question. 
            return false;
        }

        connectionStatus = ConnectionStatus.CONNECTING;

        return true;

   }

And the OnClientDataReceived Function looks like this:

   private static void OnClientDataReceived(){

      try {

         UnityEngine.Debug.Log("[TCP] Inside the try");

         while (keepServerAlive){

            UnityEngine.Debug.Log("[TCP] Inside the keep server alive");

            using (client = serverSocket.AcceptTcpClient()) {                

               UnityEngine.Debug.Log("[TCP] Inside the accept TCP Clent");
               
               // Get a stream object for reading                
               using (NetworkStream stream = client.GetStream()) {                   
                  int length;                   
                  
                  //UnityEngine.Debug.Log("Connected and waiting for incomming bytes");

                  UnityEngine.Debug.Log("[TCP] Inside the Get Stream");

                  // Read incomming stream into byte arrary.                   
                  while ( ((length = stream.Read(RxBuffer, 0, RxBuffer.Length)) != 0) && keepServerAlive) { 
                     connectionStatus = ConnectionStatus.CONNECTED; // If we are getting data, we are connected.                     
                     UnityEngine.Debug.Log("[TCP] Received " + length + " bytes");
                     comm.dataReceived(length);                     
                  }             

                  UnityEngine.Debug.Log("[TCP] After the while in the stream read");   
                
                  keepServerAlive = false;

               }             
            }            
         }

         VMLog.log("TCP Listening stopped naturally");
         connectionStatus = ConnectionStatus.NOT_CONNECTED;
         comm.rxThreadIsDone();

      }
      catch (Exception e){
         VMLog.error("Listening thread died. Reason: " + e.Message);
         connectionStatus = ConnectionStatus.NOT_CONNECTED;
         comm.rxThreadIsDone();
      }

   }

The question is: how can I modify the code of onDataReceived to be able to manually kill it withouth having to call the Thread.Abort() method and I can’t figure out how. I don’t see where I can put a boolean that gets constantly checked and when it’s value is false the thread would naturally die.

5

You could use a CancellationTokenSource & passing its CancellationToken to the thread so you can signal it when to stop. You can manage what happens when the token is cancelled inside your onDataReceived, check for the IsCancellationRequested property of a passed token.

More reading on Cancellation tokens and examples

1

You should probably change AcceptTcpClient to AcceptSocketAsync. That way you can give it a cancellation token. I would also recommend changing your code to wrap everything server related into a class, that way you can use IAsyncDisposable to simply dispose the server when you are done.

It might look something like this:

public class MyTcpServer : IAsyncDisposable
{
    private readonly TcpListener serverSocket;
    private CancellationTokenSource cancel = new CancellationTokenSource();
    private Task worker;

    public MyTcpServer(int port)
    {
        serverSocket = new TcpListener(IPAddress.Any, port);
        worker = Task.Run(Worker);
    }

    private void Worker()
    {
        while (true)
        {
            cancel.Token.ThrowIfCancellationRequested();
            using (var client = serverSocket.AcceptSocketAsync(cancel.Token))
            {
                ...
            }
        }
    }

    public async ValueTask DisposeAsync()
    {
        cancel.Cancel();
        try
        {
            await worker;
        }
        catch(OperationCanceledException){} // ignore
    }
}

you also need to decide if you want to terminate existing connections immediately, or let them continue naturally.

If you do not have any special reason to use raw TCP I would also recommend using some higher level protocol and library. There are plenty to chose from, and these tend to be much easier to use than writing your own network code, and doing raw TCP well tend to be difficult. Take a look at gRPC, AMQP or MQTT if you want somewhere to start.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật