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;
///
/// 主界面
///
public class BossWarClient : GameBehavior
{
///
/// 单例
///
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 = "";
///
/// 获取单键
///
/// 对象
public static BossWarClient Instance()
{
return pInit;
}
///
/// 初始化
///
private void Awake()
{
// 初始化
pInit = this;
}
///
/// 初始化窗体需要的各种组件
///
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();
}
}