BossWarClient.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using System;
  5. using System.Collections.Generic;
  6. using DragonBones;
  7. using UnityEngine.EventSystems;
  8. using Newtonsoft.Json.Linq;
  9. using GameFramework.Event;
  10. using UnityGameFramework.Runtime;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Threading;
  16. /// <summary>
  17. /// 主界面
  18. /// </summary>
  19. public class BossWarClient : GameBehavior
  20. {
  21. /// <summary>
  22. /// 单例
  23. /// </summary>
  24. private static BossWarClient pInit = null;
  25. static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  26. //创建1个客户端套接字和1个负责监听服务端请求的线程
  27. static Thread ThreadClient = null;
  28. private byte[] data = new byte[1024];// 数据容器
  29. private string message = "";
  30. /// <summary>
  31. /// 获取单键
  32. /// </summary>
  33. /// <returns>对象</returns>
  34. public static BossWarClient Instance()
  35. {
  36. return pInit;
  37. }
  38. /// <summary>
  39. /// 初始化
  40. /// </summary>
  41. private void Awake()
  42. {
  43. // 初始化
  44. pInit = this;
  45. }
  46. /// <summary>
  47. /// 初始化窗体需要的各种组件
  48. /// </summary>
  49. public void Start()
  50. {
  51. ConnectToServer();
  52. }
  53. void Update()
  54. {
  55. //只有在主线程才能更新UI
  56. if (message != "" && message != null)
  57. {
  58. LogHelper.Log(message);
  59. message = "";
  60. }
  61. }
  62. /**
  63. * 连接服务器端函数
  64. * */
  65. void ConnectToServer()
  66. {
  67. clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  68. //跟服务器连接
  69. clientSocket.Connect(new IPEndPoint(IPAddress.Parse("115.159.121.129"), 6002));
  70. //客户端开启线程接收数据
  71. ThreadClient = new Thread(ReceiveMessage);
  72. ThreadClient.Start();
  73. }
  74. void ReceiveMessage()
  75. {
  76. while (true)
  77. {
  78. if (clientSocket.Connected == false)
  79. {
  80. break;
  81. }
  82. int length = clientSocket.Receive(data);
  83. message = Encoding.UTF8.GetString(data, 0, length);
  84. if (message != null)
  85. {
  86. print(message);
  87. }
  88. }
  89. }
  90. new void SendMessage(string message)
  91. {
  92. byte[] data = Encoding.UTF8.GetBytes(message);
  93. clientSocket.Send(data);
  94. }
  95. public override void OnDestroy()
  96. {
  97. ThreadClient.Abort();
  98. //关闭连接,分接收功能和发送功能,both为两者均关闭
  99. clientSocket.Shutdown(SocketShutdown.Both);
  100. clientSocket.Close();
  101. }
  102. }