DCS/ruiyiweiUX/Assets/GeneralTools/Scripts/Socket/TCPClient.cs

215 lines
6.5 KiB
C#
Raw Permalink Normal View History

2026-06-09 13:59:11 +08:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using UnityEngine;
namespace GeneralTools
{
public class TCPClient : SocketBase
{
Thread threadClient = null; // 创建用于接收服务端消息的 线程;
Socket socketClient = null;
IPEndPoint endPoint;
float lastConnectedTime = -1000;
public TCPClient(string ip, int port)
{
InitSocket(ip, port);
}
//初始化
void InitSocket(string _ip, int _port)
{
IPAddress ip = IPAddress.Parse(_ip);
endPoint = new IPEndPoint(ip, _port);
threadClient = new Thread(RecMsg);
threadClient.IsBackground = true;
threadClient.Start();
}
void SocketConnet()
{
CloseClient(socketClient);
if (socketClose)
return;
if (nowTime - lastConnectedTime < reConnectedTime)
return;
lastConnectedTime = nowTime;
//定义套接字类型,必须在子线程中定义
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接
try
{
socketClient.Connect(endPoint);
}
catch (SocketException)
{
return;
}
}
void RecMsg()
{
while (true)
{
if (socketClose)
return;
byte[] arrMsgRec = new byte[reveiceByteSize];
int length = -1;
try
{
length = socketClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
}
catch (Exception e)
{
if (e.Message == "Thread was being aborted")
return;
SocketConnet();
continue;
}
if (length == 0)
{
SocketConnet();
continue;
}
//保存接收到的数据
RecordReceiveMsg(arrMsgRec, length, socketClient.LocalEndPoint, socketClient.RemoteEndPoint);
}
}
public override void SendMsg(string strMsg)
{
byte[] _sendData = String2Bytes(strMsg, encoding);
try
{
socketClient.Send(_sendData, _sendData.Length, SocketFlags.None);
}
catch (Exception se)
{
Debug.LogError(se.Message);
}
}
public override void SendMsg(byte[] byteMsg)
{
base.SendMsg(byteMsg);
try
{
socketClient.Send(byteMsg, byteMsg.Length, SocketFlags.None);
}
catch (Exception se)
{
Debug.LogError(se.Message);
}
}
public override void SocketQuit()
{
base.SocketQuit();
//关闭线程
if (threadClient != null)
{
threadClient.Interrupt();
threadClient.Abort();
}
//最后关闭socket
CloseClient(socketClient);
}
protected static void CloseClient(Socket socket)
{
if (socket != null)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
socket.Close();
socket = null;
}
}
/// <summary>
/// 发送一次TCP消息
/// </summary>
/// <param name="_ip"></param>
/// <param name="_port"></param>
/// <param name="strMsg"></param>
public static void SendMsgOnce(string _ip, int _port, string strMsg, Encoding _encoding = null)
{
Thread newThread = new Thread(() =>
{
SendOnceThread(_ip, _port, strMsg, _encoding);
});
newThread.IsBackground = true;
newThread.Start();
}
/// <summary>
/// 发送一次TCP消息
/// </summary>
/// <param name="_ip"></param>
/// <param name="_port"></param>
/// <param name="bytes"></param>
public static void SendMsgOnce(string _ip, int _port, byte[] bytes)
{
Thread newThread = new Thread(() =>
{
SendOnceThread(_ip, _port, bytes);
});
newThread.IsBackground = true;
newThread.Start();
}
protected static void SendOnceThread(string _ip, int _port, string strMsg, Encoding _encoding = null)
{
//数据类型转换
byte[] sendByte = String2Bytes(strMsg, _encoding);
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(_ip), _port);
Socket tempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接
try
{
tempSocket.Connect(ipend);
}
catch (SocketException)
{
CloseClient(tempSocket);
return;
}
try
{
tempSocket.Send(sendByte, sendByte.Length, SocketFlags.None);
}
catch (Exception)
{
CloseClient(tempSocket);
return;
}
CloseClient(tempSocket);
}
protected static void SendOnceThread(string _ip, int _port, byte[] bytes)
{
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(_ip), _port);
Socket tempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接
try
{
tempSocket.Connect(ipend);
}
catch (SocketException)
{
CloseClient(tempSocket);
return;
}
try
{
tempSocket.Send(bytes, bytes.Length, SocketFlags.None);
}
catch (Exception)
{
CloseClient(tempSocket);
return;
}
CloseClient(tempSocket);
}
}
}