Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using UnityEngine;
- public class NewBehaviourScript : MonoBehaviour
- {
- #region private members
- /// <summary>
- /// TCPListener to listen for incomming TCP connection
- /// requests.
- /// </summary>
- private TcpListener tcpListener;
- /// <summary>
- /// Background thread for TcpServer workload.
- /// </summary>
- private Thread tcpListenerThread;
- /// <summary>
- /// Create handle to connected tcp client.
- /// </summary>
- private TcpClient connectedTcpClient;
- #endregion
- // Use this for initialization
- void Start()
- {
- Debug.Log("Hello");
- // Start TcpServer background thread
- tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
- tcpListenerThread.IsBackground = true;
- tcpListenerThread.Start();
- }
- // Update is called once per frame
- void Update()
- {
- }
- void OnApplicationQuit()
- {
- Debug.Log("Application ending after " + Time.time + " seconds");
- tcpListenerThread.Abort();
- }
- /// <summary>
- /// Runs in background TcpServerThread; Handles incomming TcpClient requests
- /// </summary>
- private void ListenForIncommingRequests()
- {
- Debug.Log("Server Starting");
- try
- {
- TcpListener server = new TcpListener(IPAddress.Any, 3001);
- // we set our IP address as server's address, and we also set the port: 9999
- server.Start(); // this will start the server
- Debug.Log("Server Started");
- Socket client = server.AcceptSocket();
- while (true)
- {
- Debug.Log("Connection accepted from " + client.RemoteEndPoint);
- while (true)
- {
- string command = Console.ReadLine();
- byte[] byData = System.Text.Encoding.ASCII.GetBytes(command + "\n");
- client.Send(byData);
- byte[] b = new byte[100];
- int k = client.Receive(b);
- for (int i = 0; i < k; i++)
- Console.Write(Convert.ToChar(b[i]));
- Debug.Log("");
- }
- }
- }
- catch (Exception e)
- {
- Debug.Log("SocketException " + e.ToString());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement