using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class TcpClient : MonoBehaviour
{
//生成socket
private Socket clientSocket;
//ip地址
private IPAddress ip;
//ip和端口号
private IPEndPoint ipEnd;
//接收的数据
private byte[] recvData = new byte[1024];
//传输的数据长度
private int recvLen;
//传输的字符串
private string recvStr;
//连接开启的线程
private Thread connectThread;
//数据总长度
private int totalSize;
//包头协议
private string hexString = string.Empty;
//包体长度
private int dataLen = 0;
//发送的数据
byte[] sendData = new byte[1024];
private void Start()
{
InitSocket();
}
/// <summary>
/// 初始化socket
/// </summary>
private void InitSocket()
{
//获取ip和端口号
ip = IPAddress.Parse(IP地址);
ipEnd = new IPEndPoint(ip, 端口号);
//创建线程 在线程上运行
connectThread = new Thread(SocketReceive);
connectThread.Start();
}
/// <summary>
/// socket 接收信息
/// </summary>
private void SocketReceive()
{
SocketConnect();
//循环检测
while (true)
{
//获取数据
recvData = new byte[1024];
//获取长度
recvLen = clientSocket.Receive(recvData);
//当传输结束的时候继续挂起连接
if (recvLen == 0)
{
SocketConnect();
continue;
}
//处理数据
AnalysisData(recvData, recvLen);
}
}
/// <summary>
/// 连接socket
/// </summary>
private void SocketConnect()
{
//清理socket
if (clientSocket != null)
{
clientSocket.Close();
}
//创建socket
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//开始连接
clientSocket.Connect(ipEnd);
//进行判断
if (clientSocket.Connected)
{
Debug.Log("连接成功");
}
}
/// <summary>
/// 解析数据(前两个字节是包头,3-7是包体长度)
/// </summary>
/// <param name="bytes">传过来的数据</param>
/// <param name="length">数据长度</param>
private void AnalysisData(byte[] bytes, int length)
{
if (bytes != null && hexString == string.Empty)
{
//获取包头(前两个字节)(16进制)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2; i++)
{
sb.Append(bytes[i].ToString("X2"));
}
hexString = sb.ToString();
//获取包体3-7位(int)
byte[] dataBytesLen = new byte[4];
int index = 0;
for (int i = 4; i < 8; i++)
{
dataBytesLen[index] = bytes[i];
index++;
}
dataLen = BitConverter.ToInt32(dataBytesLen, 0);
index = 0;
byte[] dataBytes = new byte[1016];
for (int i = 8; i < bytes.Length; i++)
{
dataBytes[index] = bytes[i];
index++;
}
if (dataBytes.Length> dataLen)
{
DataDispose(dataBytes, dataLen);
}
else
{
DataDispose(dataBytes, dataBytes.Length);
}
return;
}
DataDispose(bytes, length);
}
/// <summary>
/// 数据处理
/// </summary>
/// <param name="bytes"></param>
/// <param name="length"></param>
private void DataDispose(byte[] bytes, int length)
{
//计算总长度
totalSize += length;
//获取字符串
string StringMessage2 = Encoding.UTF8.GetString(bytes, 0, length);
recvStr += StringMessage2;
//当前长度与总长度相比较
if (totalSize < dataLen)
{
return;
}
//Debug.Log(recvStr);
//如果包头是FFFF协议,按照FFFF的来处理
if (hexString == "FDFD")
{
DataManager.instance.xmlInfo = recvStr;
}
if (hexString == "FFFF")
{
DataManager.instance.jsonInfo = recvStr;
}
hexString = string.Empty;
dataLen = 0;
recvStr = string.Empty;
totalSize = 0;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="sendStr"></param>
private void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.ASCII.GetBytes(sendStr);
//发送
clientSocket.Send(sendData, sendData.Length, SocketFlags.None);
}
private void OnApplicationQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭服务器
if (clientSocket != null)
clientSocket.Close();
Debug.Log("关闭连接");
}
}
|