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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

TCP server in Unity

Discussion in 'Scripting' started by Mark-De-Clare, May 14, 2015.

  1. Mark-De-Clare

    Mark-De-Clare

    Joined:
    Aug 9, 2011
    Posts:
    63
    Is it possible to modify following code to work in Unity as a TCP server? How would you do that? I've tried to convert the Main entry point into Update-function or coroutine, but Unity 'freezes' and nothing happens.
    Why?

    Code (CSharp):
    1.  
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. using System.IO;
    8. using System.Net;
    9. using System.Net.Sockets;
    10.  
    11. namespace TCPserver
    12. {
    13.    
    14.  
    15.     class MyTcpListener
    16.     {
    17.         public static void Main()
    18.         {
    19.             TcpListener server = null;
    20.             try
    21.             {
    22.                 // Set the TcpListener on port 13000.
    23.                 Int32 port = 13000;
    24.                 IPAddress localAddr = IPAddress.Parse("192.168.1.36");
    25.  
    26.                 // TcpListener server = new TcpListener(port);
    27.                 server = new TcpListener(localAddr, port);
    28.  
    29.                 // Start listening for client requests.
    30.                 server.Start();
    31.  
    32.                 // Buffer for reading data
    33.                 Byte[] bytes = new Byte[256];
    34.                 String data = null;
    35.  
    36.                 // Enter the listening loop.
    37.                 while (true)
    38.                 {
    39.                     Console.Write("Waiting for a connection... ");
    40.  
    41.                     // Perform a blocking call to accept requests.
    42.                     // You could also user server.AcceptSocket() here.
    43.                     TcpClient client = server.AcceptTcpClient();
    44.                     Console.WriteLine("Connected!");
    45.  
    46.                     data = null;
    47.  
    48.                     // Get a stream object for reading and writing
    49.                     NetworkStream stream = client.GetStream();
    50.  
    51.                     int i;
    52.  
    53.                     // Loop to receive all the data sent by the client.
    54.                     while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    55.                     {
    56.                         // Translate data bytes to a ASCII string.
    57.                         data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    58.                         Console.WriteLine("Received: {0}", data);
    59.  
    60.                         // Process the data sent by the client.
    61.                         data = data.ToUpper();
    62.  
    63.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    64.  
    65.                         // Send back a response.
    66.                         stream.Write(msg, 0, msg.Length);
    67.                         Console.WriteLine("Sent: {0}", data);
    68.                     }
    69.  
    70.                     // Shutdown and end connection
    71.                     client.Close();
    72.                 }
    73.             }
    74.             catch (SocketException e)
    75.             {
    76.                 Console.WriteLine("SocketException: {0}", e);
    77.             }
    78.             finally
    79.             {
    80.                 // Stop listening for new clients.
    81.                 server.Stop();
    82.             }
    83.  
    84.  
    85.             Console.WriteLine("\nHit enter to continue...");
    86.             Console.Read();
    87.         }
    88.     }
    89. }
    90.  
    91.  
    92.  
     
    Last edited: May 14, 2015
  2. Jamster

    Jamster

    Joined:
    Apr 28, 2012
    Posts:
    1,102
    I was going to do it for you... but it's not simple.. :/

    Firstly make sure you class inherits from Monobehaviour then you need to put all the setup code into either Awake or Start. I would then start a coroutine for the while loop because that's what's freezing your code, it never exits the while loop to continue rendering/physic-ing/etc. :/ Finally you need to convert all the Console.WriteLine statements to Debug.Log so you can see the output.

    Networking code can be annoying at times, trust me...
     
  3. Mark-De-Clare

    Mark-De-Clare

    Joined:
    Aug 9, 2011
    Posts:
    63
    Thanks for the reply. Thats actually what I've already done, but the code is still freezing:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Net.Sockets;
    4. using System.Net;
    5. using System.IO;
    6. using System.Text;
    7. using System;
    8. public class TCPserver:MonoBehaviour{
    9.     public bool isConnection;
    10.     // Use this for initialization
    11.     void Start(){
    12.         isConnection=false;
    13.         print ("StartCoroutine");
    14.         StartCoroutine(Update1());
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     IEnumerator Update1()
    19.     {  
    20.         TcpListener server=null;  
    21.         try
    22.         {
    23.             // Set the TcpListener on port 13000.
    24.             Int32 port = 13000;
    25.             IPAddress localAddr = IPAddress.Parse("192.168.1.36");
    26.            
    27.             // TcpListener server = new TcpListener(port);
    28.             server = new TcpListener(localAddr, port);
    29.            
    30.             // Start listening for client requests.
    31.             server.Start();
    32.            
    33.             // Buffer for reading data
    34.             Byte[] bytes = new Byte[256];
    35.             String data = null;
    36.            
    37.             // Enter the listening loop.
    38.             while(!isConnection)
    39.             {
    40.                 Debug.Log("Waiting for a connection... ");
    41.                
    42.                 // Perform a blocking call to accept requests.
    43.                 // You could also user server.AcceptSocket() here.
    44.                 TcpClient client = server.AcceptTcpClient();  
    45.                 if(client!=null){
    46.  
    47.                     Debug.Log("Connected!");
    48.                     isConnection=true;
    49.                     client.Close();
    50.                     //break;
    51.  
    52.                 }
    53.                 data = null;
    54.                
    55.                 // Get a stream object for reading and writing
    56.                 NetworkStream stream = client.GetStream();
    57.                
    58.                 int i;
    59.                
    60.                 // Loop to receive all the data sent by the client.
    61.                 while((i = stream.Read(bytes, 0, bytes.Length))!=0)
    62.                 {  
    63.                     // Translate data bytes to a ASCII string.
    64.                     data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    65.                     Debug.Log("Received:"+ data);
    66.                    
    67.                     // Process the data sent by the client.
    68.                     data = data.ToUpper();
    69.                    
    70.                     byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    71.                    
    72.                     // Send back a response.
    73.                     stream.Write(msg, 0, msg.Length);
    74.                     Debug.Log("Sent:"+ data);          
    75.                 }
    76.  
    77.                 // Shutdown and end connection
    78.                 client.Close();
    79.             }
    80.         }
    81.         catch(SocketException e)
    82.         {
    83.             Debug.Log("SocketException:"+ e);
    84.         }
    85.         finally
    86.         {
    87.             // Stop listening for new clients.
    88.             server.Stop();
    89.         }
    90.  
    91.         yield return null;
    92.    
    93.    
    94.     }
    95. }
    96.  
     
  4. Mark-De-Clare

    Mark-De-Clare

    Joined:
    Aug 9, 2011
    Posts:
    63
    I used thread (using System.Threading namespace) instead of coroutine and got the code working.
     
  5. DPH

    DPH

    Joined:
    Jan 25, 2016
    Posts:
    3
    Hey would you be kind enough to post the final code, I really need it!
     
    Last edited: Mar 3, 2016
  6. Samuli Kuusisto

    Samuli Kuusisto

    Joined:
    Mar 2, 2016
    Posts:
    3
    Here's the final server code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Net.Sockets;
    5. using System.Net;
    6. using System.IO;
    7. using System.Text;
    8. using System;
    9. using System.Threading;
    10.  
    11. public class TCPserver:MonoBehaviour{
    12.     public bool isConnection,senddata1,senddata2,valuechanged,valuechanged2;
    13.     //public bool isZoomed,isPointsSet,isZooming,Zoompressed,rotatearound1,rotatearound2,rotatearound3,rotatearound4,distanceChange1,distanceChange2;
    14.     public List<string> stairways=new List<string>();
    15.     public List<bool> floorsBool = new List<bool> ();
    16.     public List<bool> roomsBool = new List<bool> ();
    17.     public List<bool> stairwaysBool = new List<bool> ();
    18.     public List<int> rooms = new List<int> ();
    19.     public List<GameObject> flats = new List<GameObject> ();
    20.     public int floors;
    21.     Zoom zoom;
    22.     ShowAndHide show;
    23.     public Thread mThread;
    24.     public TcpListener server;
    25.     public TcpClient client;
    26.     public NetworkStream stream;
    27.     byte[] msg1;
    28.     string toSend;
    29.     bool available,hide,show1,selection,endpointChanged,parsedata;
    30.     public String data,prevdata;
    31.     float frametime=0.0f;
    32.     int q=0;
    33.     int FPS=0;
    34.     GameObject building;
    35.     Vector3 pos;
    36.     Sun1 sun;
    37.     WindowLight wl;
    38.     GameObject shader;
    39.     // Use this for initialization
    40.     void Start(){
    41.         shader=GameObject.FindGameObjectWithTag ("Shader");
    42.         building=GameObject.FindGameObjectWithTag("Building");
    43.         sun = GameObject.FindGameObjectWithTag ("Light").GetComponent<Sun1> ();
    44.         wl = GameObject.FindGameObjectWithTag ("Light").GetComponent<WindowLight> ();
    45.         flats = getFlats ();
    46.         floorsBool=InitializeFloorsBool ();
    47.         roomsBool = InitializeRoomsBool ();
    48.         stairwaysBool = InitializeStairwaysBool ();
    49.         zoom = Camera.main.GetComponent<Zoom> ();
    50.         show = Camera.main.GetComponent<ShowAndHide> ();
    51.         isConnection=false;
    52.         senddata1 = false;
    53.         senddata2 = false;
    54.         //print ("StartThread");
    55.         ThreadStart ts = new ThreadStart(Update1);
    56.         mThread = new Thread(ts);
    57.         mThread.Start();
    58.     }
    59.     IEnumerator startThings(){
    60.         for(int j=0;j<flats.Count;j++){
    61.            
    62.             StartCoroutine(parseName(flats[j]));
    63.             yield return null;
    64.         }
    65.         yield return null;
    66.     }
    67.     // Update is called once per frame
    68.     void Update(){
    69.         //print (data);
    70.         //FPScounter();
    71.         if(hide){
    72.             //print ("Hide:"+building.name);
    73.             StartCoroutine(show.Hide(building,4,5.8f,6.5f,0.0025f));
    74.             StartCoroutine(show.Hide(building,3,6.1f,6.4f,0.0025f));
    75.             StartCoroutine(show.Hide(building,2,5.8f,6.1f,0.0025f));
    76.             StartCoroutine(show.Hide(building,1,6.1f,6.4f,0.0025f));
    77.             StartCoroutine(show.Hide(building,0,5.8f,6.4f,0.0025f));
    78.             hide=false;
    79.             for(int i=0;i<533;i++){
    80.                 wl.windows[i].SetActive(false);
    81.             }
    82.             shader.SetActive(false);
    83.         }
    84.         if(show1){
    85.             //print ("Hide:"+building.name);
    86.             StartCoroutine(show.Show(building,4,5.8f,6.5f,0.0025f));
    87.             StartCoroutine(show.Show(building,3,6.1f,6.4f,0.0025f));
    88.             StartCoroutine(show.Show(building,2,5.8f,6.1f,0.0025f));
    89.             StartCoroutine(show.Show(building,1,6.1f,6.4f,0.0025f));
    90.             StartCoroutine(show.Show(building,0,5.8f,6.4f,0.0025f));
    91.             show1=false;
    92.  
    93.         }
    94.         if (parsedata) {
    95.             parsedata=false;
    96.             StartCoroutine(parseData(prevdata));
    97.         }
    98.         if(selection){
    99.             selection=false;
    100.             StartCoroutine(startThings());
    101.         }
    102.         if(senddata1){
    103.             senddata1=false;
    104.             ZoomIn();
    105.         }
    106.         if(senddata2){
    107.             senddata2=false;
    108.             ZoomBack();
    109.         }
    110.         if(valuechanged){
    111.             toSend =zoom.isZooming.ToString()+",";
    112.             prevdata=toSend;
    113.             //print (toSend);
    114.             msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    115.             stream.Write (msg1, 0, msg1.Length);
    116.             valuechanged=false;
    117.         }
    118.         if(valuechanged2){
    119.             toSend =zoom.isZoomed.ToString()+":";
    120.             prevdata=toSend;
    121.             //print (toSend);
    122.             msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    123.             stream.Write (msg1, 0, msg1.Length);
    124.             valuechanged2=false;
    125.         }
    126.         if(endpointChanged){
    127.             endpointChanged=false;
    128.             zoom.Zoompoint.position=pos;
    129.             zoom.Zoompoint.rotation=Quaternion.Euler(40.0f,275.0f,0.0f);
    130.             zoom.rotateAroundObject.position=new Vector3(pos.x-0.498778f,pos.y-0.423f,pos.z-0.074f);
    131.         }
    132.     }
    133.     void FPScounter(){
    134.         frametime+=Time.deltaTime;
    135.         q++;
    136.         if(frametime>=1.0f){
    137.             FPS=q;
    138.             //print ("FPS:"+FPS);
    139.             q=0;
    140.             frametime=0.0f;
    141.         }
    142.     }
    143.     void OnApplicationQuit(){
    144.         server.Stop();
    145.         mThread.Abort ();
    146.     }
    147.     void Update1()
    148.     {  
    149.         server=null;  
    150.         try
    151.         {
    152.             // Set the TcpListener on port 13000.
    153.             Int32 port = 3333;
    154.             IPAddress localAddr = IPAddress.Parse("192.168.0.242");
    155.            
    156.             // TcpListener server = new TcpListener(port);
    157.             server = new TcpListener(IPAddress.Any, port);
    158.            
    159.             // Start listening for client requests.
    160.             server.Start();
    161.            
    162.             // Buffer for reading data
    163.             Byte[] bytes = new Byte[256];
    164.             String data = null;
    165.            
    166.             // Enter the listening loop.
    167.             while(true)
    168.             {
    169.                 Thread.Sleep(10);
    170.                
    171.                 Debug.Log("Waiting for a connection... ");
    172.                
    173.                 // Perform a blocking call to accept requests.
    174.                 // You could also user server.AcceptSocket() here.
    175.                 client = server.AcceptTcpClient();  
    176.                 if(client!=null){
    177.                    
    178.                     Debug.Log("Connected!");
    179.                     //isConnection=true;
    180.                     //client.Close();
    181.                     //break;
    182.                    
    183.                 }
    184.                 data = null;
    185.                
    186.                 // Get a stream object for reading and writing
    187.                 stream = client.GetStream();
    188.                 StreamWriter swriter=new StreamWriter(stream);
    189.                 int i;
    190.                
    191.                 // Loop to receive all the data sent by the client.
    192.                 while((i = stream.Read(bytes, 0, bytes.Length))!=0)
    193.                 {  
    194.                     //msg1 = System.Text.Encoding.ASCII.GetBytes(prevdata);
    195.                    
    196.                     // Send back a response.
    197.                     //stream.Write(msg1, 0, msg1.Length);
    198.                     // Translate data bytes to a ASCII string.
    199.                     data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    200.                     //Debug.Log("Received:"+ data+"data");
    201.                    
    202.                    
    203.                     //Debug.Log("Sent:"+ data);
    204.                     // Process the data sent by the client.
    205.                     bool isTrue=false;
    206.                     switch (data)
    207.                     {
    208.                     case "params":
    209.                         //senddata=true;
    210.                         string stairways1 = Stairways ();
    211.                         string rooms1 = Rooms ();
    212.                         toSend = floors.ToString () + "/" + stairways1 + "/" + rooms1;
    213.                         //print (toSend);
    214.                         prevdata=toSend;
    215.                         msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    216.                         stream.Write (msg1, 0, msg1.Length);
    217.                         //stream.Flush();
    218.                         break;
    219.                        
    220.                     case "isZooming":
    221.                         toSend =zoom.isZooming.ToString()+",";
    222.                         //print (toSend);
    223.                         prevdata=toSend;
    224.                         msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    225.                         stream.Write (msg1, 0, msg1.Length);
    226.                         //stream.Flush();
    227.                         break;
    228.                     case "isZoomed":
    229.                         toSend =zoom.isZoomed.ToString()+":";
    230.                         prevdata=toSend;
    231.                         //print (toSend);
    232.                         msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    233.                         stream.Write (msg1, 0, msg1.Length);
    234.                         stream.Flush();
    235.                         break;
    236.                         break;
    237.                     case "Zoompressed1,true":
    238.                         senddata1=true;
    239.                        
    240.                         //stream.Flush();
    241.                         break;
    242.                     case "Zoompressed2,true":
    243.                         senddata2=true;
    244.                        
    245.                         break;
    246.                     case "Left,true":
    247.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    248.                         //stream.Write (msg1, 0, msg1.Length);
    249.                         zoom.rotatearound1=true;
    250.                         break;
    251.                     case "Left,Stop":
    252.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    253.                         //stream.Write (msg1, 0, msg1.Length);
    254.                         zoom.rotatearound1=false;
    255.                         break;
    256.                     case "Right,true":
    257.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    258.                         //stream.Write (msg1, 0, msg1.Length);
    259.                         zoom.rotatearound2=true;
    260.                         break;
    261.                     case "Right,Stop":
    262.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    263.                         //stream.Write (msg1, 0, msg1.Length);
    264.                         zoom.rotatearound2=false;
    265.                         break;
    266.                     case "Up,true":
    267.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    268.                         //stream.Write (msg1, 0, msg1.Length);
    269.                         zoom.rotatearound3=true;
    270.                         break;
    271.                     case "Up,Stop":
    272.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    273.                         //stream.Write (msg1, 0, msg1.Length);
    274.                         zoom.rotatearound3=false;
    275.                         break;
    276.                     case "Down,true":
    277.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    278.                         //stream.Write (msg1, 0, msg1.Length);
    279.                         zoom.rotatearound4=true;
    280.                         break;
    281.                     case "Down,Stop":
    282.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    283.                         //stream.Write (msg1, 0, msg1.Length);
    284.                         zoom.rotatearound4=false;
    285.                         break;
    286.                     case "ZoomIn,true":
    287.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    288.                         //stream.Write (msg1, 0, msg1.Length);
    289.                         zoom.distanceChange1=true;
    290.                         break;
    291.                     case "ZoomIn,Stop":
    292.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    293.                         //stream.Write (msg1, 0, msg1.Length);
    294.                         zoom.distanceChange1=false;
    295.                         break;
    296.                     case "ZoomOut,true":
    297.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    298.                         //stream.Write (msg1, 0, msg1.Length);
    299.                         zoom.distanceChange2=true;
    300.                         break;
    301.                     case "ZoomOut,Stop":
    302.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    303.                         //stream.Write (msg1, 0, msg1.Length);
    304.                         zoom.distanceChange2=false;
    305.                         break;
    306.                     case "Disconnect":
    307.                         goto q;
    308.                         client.Close();
    309.                         break;
    310.                     case "Show":
    311.                         show1=true;
    312.                         break;
    313.                     case "Hide":
    314.                         hide=true;
    315.  
    316.                         break;
    317.                     default:
    318.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(prevdata);
    319.                        
    320.                         // Send back a response.
    321.                         stream.Write(msg, 0, msg.Length);
    322.                         //isTrue=true;
    323.                         //msg1 = System.Text.Encoding.ASCII.GetBytes(data);
    324.                         //stream.Write (msg1, 0, msg1.Length);
    325.                         //senddata=true;
    326.                         //StartCoroutine(sendString1(stream));
    327.                         //sendString1(stream);
    328.                         break;
    329.                     }
    330.                     bool contains1=data.Contains("Left,Stop");
    331.                     if(contains1)zoom.rotatearound1=false;
    332.                     bool contains2=data.Contains("Right,Stop");
    333.                     if(contains2)zoom.rotatearound2=false;
    334.                     bool contains3=data.Contains("Up,Stop");
    335.                     if(contains3)zoom.rotatearound3=false;
    336.                     bool contains4=data.Contains("Down,Stop");
    337.                     if(contains4)zoom.rotatearound4=false;
    338.                     bool contains5=data.Contains("ZoomIn,Stop");
    339.                     if(contains5)zoom.distanceChange1=false;
    340.                     bool contains6=data.Contains("ZoomOut,Stop");
    341.                     if(contains6)zoom.distanceChange2=false;
    342.                     if(data.StartsWith("(")){
    343.                         //data=subS(data,'(');
    344.                         parsedata=true;
    345.                         //selection=true;
    346.  
    347.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    348.                         prevdata=data;
    349.                         //Debug.Log("SentPrevdata:"+ prevdata);
    350.                         // Send back a response.
    351.                         stream.Write(msg, 0, msg.Length);
    352.                     }
    353.                     if(data==" "){
    354.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(prevdata);
    355.                         //Debug.Log("SentPrevdata:"+ prevdata);
    356.                         // Send back a response.
    357.                         stream.Write(msg, 0, msg.Length);
    358.                     }
    359.                     if(data.StartsWith("!")){
    360.                         //Debug.Log(data);
    361.                         Vector3 vector;
    362.                         try{
    363.                         vector=parseVector3(data);
    364.                         pos=vector;
    365.                         endpointChanged=true;
    366.                         //print (vector.ToString());
    367.                         }
    368.                         catch(Exception e){
    369.                         }
    370.                     }
    371.                     if(data.StartsWith("&")){
    372.                         //Debug.Log(data);
    373.                         float timeOfDay=0.0f;
    374.                         try{
    375.                         timeOfDay=float.Parse(data.Substring(1,data.Length-1));
    376.                         sun.currentTime=timeOfDay;
    377.                         }
    378.                         catch(FormatException e){
    379.                         }
    380.                         //endpointChanged=true;
    381.                         //print (timeOfDay.ToString());
    382.                     }
    383.                     if(data.StartsWith("#")){
    384.                         //Debug.Log(data);
    385.                         float cloudiness=0.0f;
    386.                         try{
    387.                             cloudiness=float.Parse(data.Substring(1,data.Length-1));
    388.                             sun.cloudiness=cloudiness;
    389.                         }
    390.                         catch(FormatException e){
    391.                         }
    392.                         //endpointChanged=true;
    393.                         //print (cloudiness.ToString());
    394.                     }
    395.                     //Debug.Log("Sent:"+ data);
    396.                 }
    397.             q:
    398.                     show1=true;
    399.                     // Shutdown and end connection
    400.                     client.Close();
    401.             }
    402.         }
    403.         catch(SocketException e)
    404.         {
    405.             Debug.Log("SocketException:"+ e);
    406.         }
    407.         finally
    408.         {
    409.             // Stop listening for new clients.
    410.             server.Stop();
    411.         }
    412.        
    413.         //yield return null;
    414.        
    415.        
    416.     }
    417.     Vector3 parseVector3(string toParse){
    418.         Vector3 vector1;
    419.         string[] splits0=toParse.Split (new char[]{'(',')'});
    420.         string[] splits = splits0[1].Split (new char[]{','});
    421.         //string[] splits2=splits[0].Split(new char[]{'!'});
    422.         float x = float.Parse (splits[0]);
    423.         float y = float.Parse (splits[1]);
    424.         float z = float.Parse (splits[2]);
    425.         vector1 = new Vector3 (x,y,z);
    426.         return vector1;
    427.     }
    428.     List<GameObject> getFlats(){
    429.         List<GameObject> flats1 = new List<GameObject> ();
    430.         GameObject parent = GameObject.FindGameObjectWithTag ("Jsaari");
    431.         Shader shader = Shader.Find("Transparent/Diffuse");
    432.    
    433.         Color color=new Color(1.0f,1.0f,1.0f,0.1f);
    434.         //shader.material.color=color;
    435.         for (int i = 0; i < parent.transform.childCount; i++)
    436.         {
    437.  
    438.             GameObject obj = parent.transform.GetChild(i).gameObject;
    439.        
    440.  
    441.             if(obj.name.StartsWith("_")){
    442.                 Renderer r=obj.GetComponent<Renderer>();
    443.                 Material material=r.sharedMaterial;
    444.                 r.sharedMaterial.shader=shader;
    445.                 r.sharedMaterial.color=color;
    446.                 /*material.SetColor("_EmissionColor",Color.white);
    447.                 material.SetFloat("_Mode", 2);
    448.                 material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
    449.                 material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
    450.                 material.SetInt("_ZWrite", 0);
    451.                 material.DisableKeyword("_ALPHATEST_ON");
    452.                 material.EnableKeyword("_ALPHABLEND_ON");
    453.                 material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
    454.                 material.renderQueue = 3000;
    455.                 material.color=color;
    456.                 material.SetColor("_EmissionColor",Color.white);
    457.                 obj.GetComponent<Renderer>().sharedMaterial=material;*/
    458.                 obj.tag="Available";
    459.                 flats1.Add(obj);
    460.             }
    461.         }
    462.         return flats1;
    463.     }
    464.     IEnumerator parseName(GameObject obj){
    465.         string name = obj.name;
    466.         List<String> nameparts = new List<string> ();
    467.         string[] splits = name.Split (new char[]{'_'});
    468.         bool stairway=false, rooms1=false, floor=false;
    469.         foreach(string s in splits){
    470.             //print (s);
    471.             if(s!="")nameparts.Add(s);
    472.             yield return null;
    473.         }
    474.         //print (nameparts.Count);
    475.         int index = 0;
    476.         for(int i=0;i<nameparts.Count;i++){
    477.             switch (i){
    478.             case 0:
    479.  
    480.                 index=0;
    481.                 //print (nameparts[i]);
    482.                 switch(nameparts[i]){
    483.                 case "a":
    484.                     index=0;
    485.                     yield return null;
    486.                     break;
    487.                 case "b":
    488.                     index=1;
    489.                     yield return null;
    490.                     break;
    491.                 case "c":
    492.                     index=2;
    493.                     yield return null;
    494.                     break;
    495.                 case "d":
    496.                     index=3;
    497.                     yield return null;
    498.                     break;
    499.                 case "e":
    500.                     index=4;
    501.                     yield return null;
    502.                     break;
    503.                 case "f":
    504.                     index=5;
    505.                     yield return null;
    506.                     break;
    507.                 case "g":
    508.                     index=6;
    509.                     yield return null;
    510.                     break;
    511.                 case "h":
    512.                     index=7;
    513.                     yield return null;
    514.                     break;
    515.                 case "i":
    516.                     index=8;
    517.                     yield return null;
    518.                     break;
    519.                 case "j":
    520.                     index=9;
    521.                     yield return null;
    522.                 break;
    523.                 case "k":
    524.                     index=10;
    525.                     yield return null;
    526.                     break;
    527.                 case "l":
    528.                     index=11;
    529.                     yield return null;
    530.                     break;
    531.                 case "m":
    532.                         index=12;
    533.                     yield return null;
    534.                     break;
    535.                 default:
    536.                     yield return null;
    537.                     break;
    538.                 }
    539.                 //print ("Index:"+index);
    540.                 //print ("Stairwaysbool:"+stairwaysBool[index]);
    541.                 if(stairwaysBool[index])stairway=true;
    542.                 yield return null;
    543.                 break;
    544.             case 1:
    545.                 print ("Id");
    546.                 yield return null;
    547.                 break;
    548.             case 2:
    549.  
    550.                 index=Convert.ToInt32(nameparts[i]);
    551.                 //print (index);
    552.                 //print (roomsBool[index-1]);
    553.                 if(roomsBool[index-1])rooms1=true;
    554.                 yield return null;
    555.                 break;
    556.             case 3:
    557.                 index=Convert.ToInt32(nameparts[i]);
    558.                 //print (index);
    559.                 //print (floorsBool[index-1]);
    560.                 if(floorsBool[index-1])floor=true;
    561.                 yield return null;
    562.                 break;
    563.             default:
    564.                 print ("Error");
    565.                 yield return null;
    566.                 break;
    567.             }
    568.             yield return null;
    569.         }
    570.         //print (stairway.ToString() + rooms1.ToString()+floor.ToString() +obj.CompareTag("Available").ToString());
    571.         if (stairway && rooms1 && floor && obj.CompareTag ("Available")) {
    572.             //print ("show");
    573.             Color color1 = new Color (0.0f, 0.5f, 0.8f, 0.6f);
    574.             obj.GetComponent<Renderer> ().sharedMaterial.color = color1;
    575.             //obj.GetComponent<Renderer> ().sharedMaterial.SetColor("_EmissionColor",Color.cyan);
    576.             yield return null;
    577.         }
    578.         else {
    579.             //print ("hide");
    580.             Color color1 = new Color (1.0f, 1.0f, 1.0f, 0.1f);
    581.             obj.GetComponent<Renderer> ().sharedMaterial.color = color1;
    582.             //obj.GetComponent<Renderer> ().sharedMaterial.SetColor("_EmissionColor",Color.white);
    583.             yield return null;
    584.         }
    585.         yield return null;
    586.     }
    587.     IEnumerator parseData(string data){
    588.         string s1 = subS (data,'(');
    589.  
    590.         //print (s1);
    591.         AssignList (ref stairwaysBool,s1);
    592.         string s2 = subS (data,'_');
    593.         //print (s2);
    594.         AssignList (ref floorsBool, s2);
    595.    
    596.         string s3 = subS (data,'%');
    597.         //print (s3);
    598.         AssignList (ref roomsBool,s3);
    599.         string s4 = subS (data,'$');
    600.         available = Convert.ToBoolean (s4);
    601.         selection = true;
    602.         yield return null;
    603.     }
    604.     void AssignList(ref List<bool> sBool, string s){
    605.  
    606.         String[] s31 = s.Split (new char[]{','});
    607.         for(int i=0;i<sBool.Count;i++){
    608.             for(int j=0;j<s31.Length-1;j++){
    609.                
    610.                 int a=Convert.ToInt32(s31[j]);
    611.                 //print (a);
    612.                 if(a==i){sBool[i]=true;
    613.                     break;}
    614.                 sBool[i]=false;
    615.             }
    616.         }
    617.     }
    618.     string subS(string s, char c){
    619.         string s1 = "";
    620.         int first = s.IndexOf (c);
    621.         if (first != null) {
    622.             int last=s.LastIndexOf(c);
    623.             int length=last-first-1;
    624.             if(length>0){
    625.                 s1=s.Substring(first+1,length);
    626.             }
    627.         }
    628.         return s1;
    629.     }
    630.     public void ZoomIn(){
    631.         if(!zoom.isPointsSet){
    632.             zoom.startpoint = zoom.transform.position;
    633.             zoom.endpoint = zoom.Zoompoint.position;
    634.             zoom.startrotation = zoom.transform.rotation;
    635.             zoom.endrotation = zoom.Zoompoint.rotation;
    636.             zoom.isPointsSet=true;
    637.             zoom.isZoomed=false;
    638.         }
    639.         zoom.isZooming = true;
    640.         toSend =zoom.isZooming.ToString()+",";
    641.         //print (toSend);
    642.         msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    643.         stream.Write (msg1, 0, msg1.Length);
    644.         zoom.Zoompressed = true;
    645.     }
    646.     public void ZoomBack(){
    647.         if(!zoom.isPointsSet){
    648.             zoom.endpoint=zoom.transform.position;
    649.             zoom.endrotation=zoom.transform.rotation;
    650.             zoom.isPointsSet=true;
    651.             zoom.isZoomed=true;
    652.         }
    653.         zoom.isZooming = true;
    654.         toSend =zoom.isZooming.ToString()+",";
    655.         //print (toSend);
    656.         msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    657.         stream.Write (msg1, 0, msg1.Length);
    658.         zoom.Zoompressed=true;
    659.     }
    660.     List<bool> InitializeFloorsBool(){
    661.         List<bool> list = new List<bool> ();
    662.         for(int i=0;i<floors;i++){
    663.             list.Add(true);
    664.         }
    665.         return list;
    666.     }
    667.     List<bool> InitializeRoomsBool(){
    668.         List<bool> list = new List<bool> ();
    669.         for(int i=0;i<rooms.Count;i++){
    670.             list.Add(true);
    671.         }
    672.         return list;
    673.     }
    674.     List<bool> InitializeStairwaysBool(){
    675.         List<bool> list = new List<bool> ();
    676.         for(int i=0;i<stairways.Count;i++){
    677.             list.Add(true);
    678.         }
    679.         return list;
    680.     }
    681.     IEnumerator sendString1(NetworkStream stream1){
    682.         string stairways1 = Stairways ();
    683.         string rooms1 = Rooms ();
    684.         string toSend = floors.ToString () + "/" + stairways1 + "/" + rooms1;
    685.         //print (toSend);
    686.         byte[] msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
    687.         stream1.Write (msg1, 0, msg1.Length);
    688.         yield return null;
    689.     }
    690.     string Stairways(){
    691.         string s = "";
    692.         for(int i=0; i<stairways.Count;i++){
    693.             s+=stairways[i]+",";
    694.         }
    695.         return s;
    696.     }
    697.     string Rooms(){
    698.         string s = "";
    699.         for(int i=0; i<rooms.Count;i++){
    700.             s+=rooms[i].ToString()+",";
    701.         }
    702.         return s;
    703.     }
    704. }
    705.  
     
    Andergraw likes this.
  7. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    For readability or maintenance (this also applied for 1 person project), you could split your code into more classes, each managing a specific aspect of your game.
    I see at least the following classes reading your code:
    - NetworkManager
    - CommandParser
    - CameraManager
    - Map
     
  8. Samuli Kuusisto

    Samuli Kuusisto

    Joined:
    Mar 2, 2016
    Posts:
    3
    True (but what do you mean, Map?). My excuse for writing such a code is that it was done in a hurry. It was just a demo, not final project.
     
  9. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    I see that there are objects such as floors, stairways, rooms. I guess these objects can be managed by a Map class, or Environment class.

    I know what it is to write codes in a rush ;). These are often the codes I have a hard time with when I come back at it later and I don't remember what the hell I was thinking about while writing that.

    It's a good habit to have you code organized from the start, It would safe you from trouble later on. Also, if it is organized from the start, that's something you don't have to do anymore, which means more time to do something else!
     
  10. Samuli Kuusisto

    Samuli Kuusisto

    Joined:
    Mar 2, 2016
    Posts:
    3
    Environment class would suit better in that case.

    I'm also often confused when I read own old code trying to figure out the logic behind it.

    I think I've learned my lesson, from now on I'll organize the code better from the start.

    I hope DPH can still find the information needed from that relatively unorganized code.
     
  11. DPH

    DPH

    Joined:
    Jan 25, 2016
    Posts:
    3
    I'm kinda new to Unity/C# so yeah it is a bit overwhelming! My goal is to make a TCP server to read anything (string, float etc.) and to use them to move my humanoid avatar (big school project).
     
  12. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    In case you're really that new, that could be some heavy stuff to start with.

    Have you tried Unity's build-in networking? It's UDP based as far as i can recall but also offers configurations to achieve reliability, in order delivery etc.
    Unless you don't need to send it via a secure stream such as (SSL/TLS based) you should be fine to go with it.

    If you still aim for your own system you're probably better off starting with a clean base, i know MSDN examples are not the best but it's what i had started with to get a basic idea of everything and which is still the base for my networking system's prototype.
    You can find synchronous client-server and asynchronous client-server samples here. I personally had to change them alot as the example is quite useless for gaming, but you'll get the idea.
     
  13. Andergraw

    Andergraw

    Joined:
    Nov 28, 2016
    Posts:
    6
    Thank you very much for your code, @Samuli. It's been really helpful.
     
  14. Kaweri

    Kaweri

    Joined:
    Jan 6, 2020
    Posts:
    2
    Thank you very much for your code @Samuli