Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

TCP/IP

Discussion in 'Getting Started' started by elrana112, Feb 23, 2020.

  1. elrana112

    elrana112

    Joined:
    Oct 10, 2019
    Posts:
    6
    Hello, all!
    I am trying to make a TCP/IP connection in unity(unity as a server), but when I run my application, it seems there is something in the code that keeps unity from starting
    My code is:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.Linq;
    6. using System.Text;
    7. using System.Threading.Tasks;
    8.  
    9. using System.Net;
    10. using System.Net.Sockets;
    11. public class test: MonoBehaviour {
    12. void Start()
    13. {
    14.    
    15.             TcpListener listen = new TcpListener(IPAddress.Any, 1234);
    16.             Console.WriteLine("listening ...");
    17.             listen.Start();
    18.             TcpClient client = listen.AcceptTcpClient();
    19.             NetworkStream stream = client.GetStream();
    20.             while (true)
    21.             {
    22.              
    23.                 Console.WriteLine("connected");
    24.                
    25.  
    26.                 byte[] buffer = new byte[720];
    27.                 int data = stream.Read(buffer, 0, 720);
    28.             }
    29. }
    30. }
    I have tried this code as a standalone C# project and it works fine
    Anyone have an idea of what is happening?
     
    Last edited: Feb 23, 2020
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    Unity's MonoBehaviour-based scripting system is single-threaded and runs on the main thread. When Unity loads a scene for the first time it will call every Start() function on every script attached to every game object, and it won't move onto the next task until they're finished.

    An infinite loop in your Start() function means it will never move on.
    Code (csharp):
    1. while (true)
    https://docs.unity3d.com/Manual/ExecutionOrder.html

    Show us the code you wrote for the standalone project.
     
    Last edited: Feb 23, 2020
  3. elrana112

    elrana112

    Joined:
    Oct 10, 2019
    Posts:
    6
    Hello!
    I tried the codes in this link as two standalone project in Visual Studio at first https://www.c-sharpcorner.com/artic..._DoMXGG68WQ7SQ7NhyRmqimaAwDMYatp8yr8H9msC-qOw, which works fine
    While attempting to run it, here is what I face: upload_2020-2-23_14-3-52.png
    And I am forced to close it from task manager
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    Right. That's precisely how the editor will behave when an infinite loop is entered. Because just like Unity it is running on the main thread.

    Right. It's working fine because it has code that checks for a condition and once it is met breaks out of the loop. You need to add a similar section to the script you posted earlier starting after line 27.

    Code (csharp):
    1. if (data.IndexOf("<EOF>") > -1)
    2. {
    3.     break;
    4. }
     
    Last edited: Feb 23, 2020
    JoeStrout likes this.
  5. elrana112

    elrana112

    Joined:
    Oct 10, 2019
    Posts:
    6
    Ok, what if I do not know the data incoming. I mean that the example I am following in this link is just for checking the protocol works fine in Unity. My incoming data would be a stream of bytes. Should I manage that by checking if the length is completed or not?
     
  6. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    I have very limited experience with networking. My first thought would be to have the code for handling reading and writing across the stream in its own thread and use queues to pass the data between the main thread and the network thread.

    This question would be better answered by someone experienced in networking like @JoeStrout.
     
  7. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,851
    This is exactly right. The only way to service a socket properly is to do it in its own thread.
     
    mcroswell likes this.
  8. elrana112

    elrana112

    Joined:
    Oct 10, 2019
    Posts:
    6
    Okay, I am trying to figure how to use threading in my unity application, and these two codes that work fine as standalone C# applications
    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using System.Net;
    4. using System.Net.Sockets;
    5.  
    6. public class EchoClient {
    7.   public static void Main(){
    8.    try {
    9.     TcpClient client = new TcpClient("192.168.1.4", 9000);
    10.     StreamReader reader = new StreamReader(client.GetStream());
    11.     StreamWriter writer = new StreamWriter(client.GetStream());
    12.     String s = String.Empty;
    13.     while(!s.Equals("Exit")){
    14.      Console.Write("Enter a string to send to the server: ");
    15.      s = Console.ReadLine();
    16.      Console.WriteLine();
    17.      writer.WriteLine(s);
    18.      writer.Flush();
    19.      String server_string = reader.ReadLine();
    20.      Console.WriteLine(server_string);
    21.     }
    22.     reader.Close();
    23.     writer.Close();
    24.     client.Close();
    25.     } catch(Exception e){
    26.       Console.WriteLine(e);
    27.     }
    28.  
    29.   Console.ReadLine();
    30.   }
    31. }
    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using System.Net;
    4. using System.Net.Sockets;
    5. using System.Threading;
    6.  
    7. public class MultiThreadedEchoServer {
    8.  
    9.     private static void ProcessClientRequests(object argument){
    10.         TcpClient client = (TcpClient)argument;
    11.         try {
    12.             StreamReader reader = new StreamReader(client.GetStream());
    13.             StreamWriter writer = new StreamWriter(client.GetStream());
    14.             string s = String.Empty;
    15.             while(!(s = reader.ReadLine()).Equals("Exit") || (s == null)){
    16.                 Console.WriteLine("From client -> " + s);
    17.                 writer.WriteLine("From server -> " + s);
    18.                 writer.Flush();
    19.             }
    20.             reader.Close();
    21.             writer.Close();
    22.             client.Close();
    23.             Console.WriteLine("Closing client connection!");
    24.         } catch(IOException){
    25.                 Console.WriteLine("Problem with client communication. Exiting thread.");
    26.         } finally{
    27.                 if(client != null){
    28.                     client.Close();
    29.                 }
    30.         }  
    31.     }
    32.  
    33.     public static void Main(){
    34.         TcpListener listener = null;
    35.         try {
    36.             listener = new TcpListener(IPAddress.Parse("192.168.1.4"), 9000);
    37.             listener.Start();
    38.             Console.WriteLine("MultiThreadedEchoServer started...");
    39.             while(true){
    40.                 Console.WriteLine("Waiting for incoming client connections...");
    41.                 TcpClient client = listener.AcceptTcpClient();
    42.                 Console.WriteLine("Accepted new client connection...");
    43.                 Thread t = new Thread(ProcessClientRequests);
    44.                 t.Start(client);
    45.             }
    46.         } catch(Exception e){
    47.                 Console.WriteLine(e);
    48.         } finally{
    49.                 if(listener != null){
    50.                     listener.Stop();
    51.                 }
    52.         }
    53.         Console.ReadLine();
    54.   }
    55. }
    And the same thing happens to unity...