Advertisement
Guest User

Problem with thread exception

a guest
Feb 17th, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9.  
  10. public class ConnectionsHandler : MonoBehaviour
  11. {
  12.     private static Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  13.     public GameObject ConnectButton;
  14.     public GameObject SendButton;
  15.     public Text ipAdress;
  16.     public Text port;
  17.     public Text serverResponse;
  18.     public Text textToBeSent;
  19.     private bool Connected;
  20.  
  21.     void Start()
  22.     {
  23.         Connected = false;
  24.     }
  25.  
  26.     public void ConnectToServer()
  27.     {
  28.         int attempts = 0;
  29.         while (!ServerSocket.Connected)
  30.         {
  31.             try
  32.             {
  33.                 attempts++;
  34.                 ServerSocket.Connect(IPAddress.Parse(ipAdress.text), int.Parse(port.text));
  35.             }
  36.             catch (SocketException)
  37.             {
  38.                 Debug.Log("Connection attempts: " + attempts.ToString());
  39.             }
  40.             if (attempts >= 4)
  41.             {
  42.                 return;
  43.             }
  44.         }
  45.         Debug.Log("Connected");
  46.         serverResponse.text = "Connected with Server";
  47.         Connected = true;
  48.     }
  49.  
  50.     public void SendTextStream()
  51.     {
  52.         if (Connected == true)
  53.         {
  54.             if (textToBeSent.text != string.Empty)
  55.             {
  56.                 string text = textToBeSent.text;
  57.                 byte[] buffer = Encoding.ASCII.GetBytes(text);
  58.                 ServerSocket.Send(buffer);
  59.                 textToBeSent.text = string.Empty;
  60.                 StartCoroutine_Auto(CatchFilesLoop());
  61.             }
  62.         }
  63.     }
  64.  
  65.     IEnumerator CatchFilesLoop()
  66.     {
  67.         yield return new WaitForSeconds(1f);
  68.         byte[] receivedBuf = new byte[1024];
  69.         int rec = ServerSocket.Receive(receivedBuf);
  70.         byte[] data = new byte[rec];
  71.         Array.Copy(receivedBuf, data, rec);
  72.         serverResponse.text = Encoding.ASCII.GetString(data);
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement