123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- using System;
- using System.Collections.Generic;
- using DragonBones;
- using UnityEngine.EventSystems;
- using Newtonsoft.Json.Linq;
- using GameFramework.Event;
- using UnityGameFramework.Runtime;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- /// <summary>
- /// 主界面
- /// </summary>
- public class BossWarClient : GameBehavior
- {
- /// <summary>
- /// 单例
- /// </summary>
- private static BossWarClient pInit = null;
- static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //创建1个客户端套接字和1个负责监听服务端请求的线程
- static Thread ThreadClient = null;
- private byte[] data = new byte[1024];// 数据容器
- private string message = "";
- /// <summary>
- /// 获取单键
- /// </summary>
- /// <returns>对象</returns>
- public static BossWarClient Instance()
- {
- return pInit;
- }
- /// <summary>
- /// 初始化
- /// </summary>
- private void Awake()
- {
- // 初始化
- pInit = this;
- }
- /// <summary>
- /// 初始化窗体需要的各种组件
- /// </summary>
- public void Start()
- {
- ConnectToServer();
- }
- void Update()
- {
- //只有在主线程才能更新UI
- if (message != "" && message != null)
- {
- LogHelper.Log(message);
- message = "";
- }
- }
- /**
- * 连接服务器端函数
- * */
- void ConnectToServer()
- {
- clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //跟服务器连接
- clientSocket.Connect(new IPEndPoint(IPAddress.Parse("115.159.121.129"), 6002));
- //客户端开启线程接收数据
- ThreadClient = new Thread(ReceiveMessage);
- ThreadClient.Start();
- }
- void ReceiveMessage()
- {
- while (true)
- {
- if (clientSocket.Connected == false)
- {
- break;
- }
- int length = clientSocket.Receive(data);
- message = Encoding.UTF8.GetString(data, 0, length);
- if (message != null)
- {
- print(message);
- }
- }
- }
- new void SendMessage(string message)
- {
- byte[] data = Encoding.UTF8.GetBytes(message);
- clientSocket.Send(data);
- }
- public override void OnDestroy()
- {
- ThreadClient.Abort();
- //关闭连接,分接收功能和发送功能,both为两者均关闭
- clientSocket.Shutdown(SocketShutdown.Both);
- clientSocket.Close();
- }
- }
|