Files
1440WGJ/SocketHelper/TCPClient.cs
T
2026-07-14 13:55:17 +08:00

257 lines
7.6 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocketHelper
{
public class TCPClient
{
#region 属性
private string _serverip;
/// <summary>
/// 服务端IP
/// </summary>
public string ServerIp
{
set { _serverip = value; }
get { return _serverip; }
}
private int _serverport;
/// <summary>
/// 服务端监听端口
/// </summary>
public int ServerPort
{
set { _serverport = value; }
get { return _serverport; }
}
private TcpClient _tcpclient = null;
/// <summary>
/// TcpClient客户端
/// </summary>
public TcpClient Tcpclient
{
set { _tcpclient = value; }
get { return _tcpclient; }
}
private Thread _tcpthread = null;
/// <summary>
/// Tcp客户端连接线程
/// </summary>
public Thread Tcpthread
{
set { _tcpthread = value; }
get { return _tcpthread; }
}
private bool _isStarttcpthreading = false;
/// <summary>
/// 是否启动Tcp连接线程
/// </summary>
public bool IsStartTcpthreading
{
set { _isStarttcpthreading = value; }
get { return _isStarttcpthreading; }
}
private bool _isclosed;
/// <summary>
/// 连接是否关闭
/// </summary>
public bool Isclosed
{
set { _isclosed = value; }
get { return _isclosed; }
}
private string _receivestr;
/// <summary>
/// 接收Socket数据包 缓存字符串
/// </summary>
public string Receivestr
{
set { _receivestr = value; }
get { return _receivestr; }
}
/// <summary>
/// 重连次数
/// </summary>
private int _reConectedCount = 0;
public int ReConectedCount {
get { return _reConectedCount; }
set { _reConectedCount = value; }
}
#endregion
#region 方法
/// <summary>
/// 十六进制字字符串转为节数组
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static byte[] StringToHexByteArray(string s)
{
s = s.Replace(" ", "");
if ((s.Length % 2) != 0)
s += " ";
byte[] returnBytes = new byte[s.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 启动连接Socket服务器
/// </summary>
public void StartConnection()
{
try
{
Isclosed = false;
CreateTcpClient();
}
catch (Exception ex)
{
//LogHelper.WriteLog(ex.Message);
DelegateHelper.SocketInfo("错误信息:" + ex.Message);
}
}
/// <summary>
/// 创建线程连接
/// </summary>
private void CreateTcpClient()
{
if (Isclosed)
return;
Tcpclient = new TcpClient();
Tcpthread = new Thread(StartTcpThread);
IsStartTcpthreading = true;
Tcpthread.Start();
}
/// <summary>
/// 线程接收Socket上传的数据
/// </summary>
private void StartTcpThread()
{
byte[] receivebyte = new byte[128];
int bytelen;
try
{
while (IsStartTcpthreading)
{
if (!Tcpclient.Connected)
{
try
{
if (ReConectedCount != 0)
{
DelegateHelper.SocketInfo(string.Format("正在第{0}次重新连接FMS服务器... ...", ReConectedCount));
}
else
{
DelegateHelper.SocketInfo("正在连接FMS服务器... ...");
}
Tcpclient.Connect(IPAddress.Parse(ServerIp), ServerPort);
DelegateHelper.SocketInfo("已连接FMS服务器");
}
catch
{
//连接失败
ReConectedCount++;
IsStartTcpthreading = false;
Thread.Sleep(3000);
continue;
}
}
bytelen = Tcpclient.Client.Receive(receivebyte);
// 连接断开
if (bytelen == 0)
{
DelegateHelper.SocketInfo("与服务器断开连接... ...");
ReConectedCount = 1;
IsStartTcpthreading = false;
continue;
}
Receivestr = ASCIIEncoding.Default.GetString(receivebyte, 0, bytelen);
if (Receivestr.Trim() != "")
{
//接收数据
DelegateHelper.SocketReceive(Receivestr);
}
}
CreateTcpClient();
}
catch (Exception ex)
{
// 异常退出时、需要重新连接
CreateTcpClient();
DelegateHelper.SocketInfo("错误信息:" + ex.Message);
}
}
/// <summary>
/// 发送Socket消息
/// </summary>
/// <param name="cmdstr"></param>
public void SendCommand(string cmdstr)
{
try
{
//byte[] _out=Encoding.GetEncoding("GBK").GetBytes(cmdstr);
byte[] _out = Encoding.Default.GetBytes(cmdstr);
Tcpclient.Client.Send(_out);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 发送Socket消息
/// </summary>
/// <param name="byteMsg"></param>
public void SendCommand(byte[] byteMsg)
{
try
{
Tcpclient.Client.Send(byteMsg);
}
catch (Exception ex)
{
DelegateHelper.SocketInfo("错误信息:" + ex.Message);
}
}
#endregion
public void Close()
{
try
{
if (Tcpclient.Client.Connected)
{
Tcpclient.Client.Close();
Tcpclient.Client.Disconnect(true);
}
}
catch (Exception ex)
{
DelegateHelper.SocketInfo("错误信息:" + ex.Message);
}
}
#region 构造函数
/// <summary>
/// 初始化TCPClient类
/// </summary>
/// <param name="ip">服务端IP</param>
/// <param name="port">监听端口</param>
public TCPClient(string ip, int port)
{
ServerIp = ip;
ServerPort = port;
}
#endregion
}
}