Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using System;
- using System.Text;
- using System.Collections;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- public class ConnectionsHandler : MonoBehaviour
- {
- private static Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- public GameObject ConnectButton;
- public GameObject SendButton;
- public Text ipAdress;
- public Text port;
- public Text serverResponse;
- public Text textToBeSent;
- private bool Connected;
- void Start()
- {
- Connected = false;
- }
- public void ConnectToServer()
- {
- int attempts = 0;
- while (!ServerSocket.Connected)
- {
- try
- {
- attempts++;
- ServerSocket.Connect(IPAddress.Parse(ipAdress.text), int.Parse(port.text));
- }
- catch (SocketException)
- {
- Debug.Log("Connection attempts: " + attempts.ToString());
- }
- if (attempts >= 4)
- {
- return;
- }
- }
- Debug.Log("Connected");
- serverResponse.text = "Connected with Server";
- Connected = true;
- }
- public void SendTextStream()
- {
- if (Connected == true)
- {
- if (textToBeSent.text != string.Empty)
- {
- string text = textToBeSent.text;
- byte[] buffer = Encoding.ASCII.GetBytes(text);
- ServerSocket.Send(buffer);
- textToBeSent.text = string.Empty;
- StartCoroutine_Auto(CatchFilesLoop());
- }
- }
- }
- IEnumerator CatchFilesLoop()
- {
- yield return new WaitForSeconds(1f);
- byte[] receivedBuf = new byte[1024];
- int rec = ServerSocket.Receive(receivedBuf);
- byte[] data = new byte[rec];
- Array.Copy(receivedBuf, data, rec);
- serverResponse.text = Encoding.ASCII.GetString(data);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement