Advertisement
SkyFlash21

Server-TCP-Unity

Jul 14th, 2021 (edited)
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using UnityEngine;
  6.  
  7. public class NewBehaviourScript : MonoBehaviour
  8. {
  9. #region private members
  10. /// <summary>
  11. /// TCPListener to listen for incomming TCP connection
  12. /// requests.
  13. /// </summary>
  14. private TcpListener tcpListener;
  15. /// <summary>
  16. /// Background thread for TcpServer workload.
  17. /// </summary>
  18. private Thread tcpListenerThread;
  19. /// <summary>
  20. /// Create handle to connected tcp client.
  21. /// </summary>
  22. private TcpClient connectedTcpClient;
  23. #endregion
  24.  
  25. // Use this for initialization
  26. void Start()
  27. {
  28. Debug.Log("Hello");
  29. // Start TcpServer background thread
  30. tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
  31. tcpListenerThread.IsBackground = true;
  32. tcpListenerThread.Start();
  33. }
  34.  
  35. // Update is called once per frame
  36. void Update()
  37. {
  38. }
  39.  
  40. void OnApplicationQuit()
  41. {
  42. Debug.Log("Application ending after " + Time.time + " seconds");
  43. tcpListenerThread.Abort();
  44. }
  45. /// <summary>
  46. /// Runs in background TcpServerThread; Handles incomming TcpClient requests
  47. /// </summary>
  48. private void ListenForIncommingRequests()
  49. {
  50. Debug.Log("Server Starting");
  51. try
  52. {
  53. TcpListener server = new TcpListener(IPAddress.Any, 3001);
  54. // we set our IP address as server's address, and we also set the port: 9999
  55.  
  56. server.Start(); // this will start the server
  57.  
  58. Debug.Log("Server Started");
  59. Socket client = server.AcceptSocket();
  60. while (true)
  61. {
  62.  
  63. Debug.Log("Connection accepted from " + client.RemoteEndPoint);
  64. while (true)
  65. {
  66.  
  67. string command = Console.ReadLine();
  68.  
  69. byte[] byData = System.Text.Encoding.ASCII.GetBytes(command + "\n");
  70. client.Send(byData);
  71. byte[] b = new byte[100];
  72. int k = client.Receive(b);
  73. for (int i = 0; i < k; i++)
  74. Console.Write(Convert.ToChar(b[i]));
  75. Debug.Log("");
  76. }
  77.  
  78. }
  79. }
  80. catch (Exception e)
  81. {
  82. Debug.Log("SocketException " + e.ToString());
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement