Tcp_Server.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System.Net;
  7. using System;
  8. public class Tcp_Server : MonoBehaviour {
  9. private static int tokenIndex = 0;
  10. public TextMesh textone;
  11. //配置相关;
  12. private string _ip;
  13. [SerializeField]
  14. private int _port = 50001;
  15. private Socket _server;
  16. private Thread _acceptClientConnectThread;
  17. private Dictionary<string, Tcp_Connect> _clientDictionary =new Dictionary<string, Tcp_Connect>();
  18. private bool _isActive = true;
  19. // Use this for initialization
  20. void Awake () {
  21. //_ip = Network.player.ipAddress;
  22. //for (int i = 0; i < Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length; i++)
  23. //{
  24. // if (Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].AddressFamily.ToString() == "InterNetwork")
  25. // {
  26. // _ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString();
  27. // }
  28. //}
  29. _ip = Tcp_Util.GetIP();
  30. Debug.Log("ip " + _ip + ":" + _port);
  31. }
  32. // Update is called once per frame
  33. void Update () {
  34. }
  35. void OnApplicationQuit()
  36. {
  37. Close ();
  38. }
  39. /// <summary>
  40. /// 启动服务器=建立流式套接字+配置本地地址;
  41. /// </summary>
  42. public void StartUp()
  43. {
  44. try
  45. {
  46. _isActive = true;
  47. _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  48. Debug.Log("ip " + _ip + ":" + _port);
  49. textone.text = _ip;
  50. EndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);
  51. _server.Bind(endPoint);
  52. _server.Listen(30);
  53. Debug.Log("Socket服务器监听启动......");
  54. _acceptClientConnectThread = new Thread(AcceptClientConnect);
  55. _acceptClientConnectThread.Start();
  56. }
  57. catch (Exception e)
  58. {
  59. Debug.Log (e.Message);
  60. Close ();
  61. }
  62. }
  63. /// <summary>
  64. /// Accept Client Connect接受客户端连接;
  65. /// </summary>
  66. ///
  67. public static bool isClient;
  68. public void AcceptClientConnect()
  69. {
  70. Tcp_Connect tc;
  71. string token;
  72. while (_isActive)
  73. {
  74. try
  75. {
  76. //接受客户端连接,接一次执行一次, 返回值为客户端的套接字;
  77. Socket clientSocket = _server.Accept ();
  78. Debug.Log("客户端已连接!local:" + clientSocket.LocalEndPoint + "<---Client:" + clientSocket.RemoteEndPoint);
  79. isClient=true;
  80. //维护一个客户端列表;
  81. tokenIndex++;
  82. token = "client_" + tokenIndex;
  83. tc = new Tcp_Connect (clientSocket, RemoveClient, token);
  84. tc.StartUp ();
  85. _clientDictionary.Add (token, tc);
  86. }
  87. catch (Exception e)
  88. {
  89. Debug.Log (e.Message);
  90. }
  91. _isActive = false;
  92. }
  93. _acceptClientConnectThread.Abort();
  94. }
  95. /// <summary>
  96. /// 给某个客户端发消息
  97. /// </summary>
  98. /// <param name="msg">Message.</param>
  99. /// <param name="client">Client.</param>
  100. public void Send(byte[] msg , string key)
  101. {
  102. if (_clientDictionary.ContainsKey (key)) {
  103. _clientDictionary [key].Send (msg);
  104. }
  105. }
  106. /// <summary>
  107. /// 给所有人发消息
  108. /// </summary>
  109. /// <param name="str">String.</param>
  110. public void SendAll(byte[] msg)
  111. {
  112. var enumerator = _clientDictionary.GetEnumerator();
  113. while (enumerator.MoveNext ()) {
  114. Send (msg, enumerator.Current.Key);
  115. }
  116. }
  117. public void RemoveClient(string token)
  118. {
  119. isClient = false;
  120. //Debug.Log ("duankai:==>"+token);
  121. if (_clientDictionary.ContainsKey(token)) {
  122. _clientDictionary ["token"].Close ();
  123. _clientDictionary.Remove (token);
  124. }
  125. }
  126. //最后关闭套接字;
  127. public void Close()
  128. {
  129. _isActive = false;
  130. //关闭客户端套接字相关;
  131. var enumerator = _clientDictionary.GetEnumerator();
  132. while (enumerator.MoveNext ()) {
  133. enumerator.Current.Value.Close ();
  134. }
  135. //列表清除;
  136. _clientDictionary.Clear();
  137. //关闭服务器套接字相关;
  138. if (_server != null) {
  139. _server.Close();
  140. }
  141. }
  142. }