namespace SmsService
{
public class SocketClient
{
//声明IP,端口,和一个用来连接的Socket
private string _ip;
private int _port;
private System.Net.Sockets.TcpClient _tcpClient;
private NetworkStream networkStream;
//创建一个委托,用来满足其他类调用
public delegate void DelegateMessage(byte[] bytes,TcpClient tcp);
public event DelegateMessage OnmessageEvent;
//
//private bool CanRecv = false;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="remoteIp">IP地址</param>
/// <param name="remotePort">端口号</param>
public SocketClient(string remoteIp, int remotePort)
{
this.IP = remoteIp;
this.Port = remotePort;
}
/// <summary>
/// 返回连接状态;
/// </summary>
public bool isConnected
{
get
{
if (_tcpClient==null)
{
//CanRecv = false;
return false;
}
return _tcpClient.Connected;
}
}
public string IP { get => _ip; set => _ip = value; }
public int Port { get => _port; set => _port = value; }
/// <summary>
/// TCP连接
/// </summary>
/// <param name="autoRecv">是否自动接收消息</param>
/// <returns></returns>
public bool Connect(bool autoRecv=true)
{
_tcpClient = new TcpClient();
try
{
_tcpClient.Connect(IPAddress.Parse(IP), Port);
if(autoRecv)
Task.Run(new Action(ReceiveMessageNew));//开启线程,不停接收消息
}
catch (Exception e)
{
Logger.Default.Error(e.Message);
return false;
}
return true;//返回连接状态
}
//断开连接
public void DisConnect()
{
try
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)
return;
//CanRecv = false;
_tcpClient.Close();
}
catch (Exception e)
{
Logger.Default.Error(e.Message);
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="bytes">需要发送的字节</param>
public void SendMessage(byte[] bytes)
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)//检测是否连接
return;
try
{
NetworkStream networkStream = _tcpClient.GetStream();
networkStream.Write(bytes, 0, bytes.Length);
string Msg = Encoding.Default.GetString(bytes);
if (CommonCfg.LogOn == 1)
Logger.Default.Info("send:" + Msg);
//增加,休眠指定的时间
Thread.Sleep(CommonCfg.SendWaitTime);
}
catch
{ }
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="bytes">需要发送的文本</param>
public void SendMessage(string Msg,Encoding encoding)
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)
return;
try
{
byte[] bytes = encoding.GetBytes(Msg);
NetworkStream networkStream = _tcpClient.GetStream();
networkStream.Write(bytes, 0, bytes.Length);
if(CommonCfg.LogOn==1)
Logger.Default.Info("send:" + Msg);
//增加,休眠指定的时间
Thread.Sleep(CommonCfg.SendWaitTime);
}
catch
{ }
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="bytes">需要发送的文本</param>
public void SendMessageLineAdd(string Msg)
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)
return;
try
{
byte[] bytes = Encoding.UTF8.GetBytes(Msg+Environment.NewLine);
NetworkStream networkStream = _tcpClient.GetStream();
networkStream.Write(bytes, 0, bytes.Length);
if (CommonCfg.LogOn == 1)
Logger.Default.Info("send:" + Msg);
//增加,休眠指定的时间
Thread.Sleep(CommonCfg.SendWaitTime);
}
catch
{ }
}
/// <summary>
/// 发送消息,使用WriteLine发送,自带换行
/// </summary>
/// <param name="Msg"></param>
public void SendMessageLine(string Msg)
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)
return;
try
{
networkStream = _tcpClient.GetStream();
using (StreamWriter writer = new StreamWriter(networkStream))
{
writer.WriteLine(Msg);
writer.Flush();
}
if (CommonCfg.LogOn == 1)
Logger.Default.Info("send:" + Msg);
//增加,休眠指定的时间
Thread.Sleep(CommonCfg.SendWaitTime);
}
catch
{ }
}
/// <summary>
/// DVS指令的发送消息
/// </summary>
/// <param name="Msg"></param>
public void SendDVSMsg(string Msg,string action)
{
if (_tcpClient == null)
return;
if (_tcpClient.Connected == false)
return;
//try
//{
networkStream = _tcpClient.GetStream();
byte[] buffer = StringToBytes(Msg);
networkStream.Write(buffer, 0, buffer.Length);
if (CommonCfg.LogOn == 1)
{
Logger.Default.Info(action);
Logger.Default.Info("send:" + Msg);
}
//增加,休眠指定的时间
Thread.Sleep(2000);
//}
//catch
//{ }
}
public static byte[] StringToBytes(string str)
{
byte[] bytes = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
bytes[i / 2] = (byte)Convert.ToByte(str.Substring(i, 2), 16);
return bytes;
//List<byte> buffer = new List<byte>();
//for (int i = 0; i < str.Length; i += 2)
//{
// buffer.Add(Convert.ToByte(str.Substring(i, 2), 16));
//}
//return buffer.ToArray();
}
//接收消息
private void ReceiveMessage()
{
try
{
NetworkStream networkStream = _tcpClient.GetStream();
while (isConnected)
{
if (_tcpClient.Available <= 0)//数据量小于等于0代表无数据
continue;
byte[] buffer = new byte[102400];
if(networkStream.DataAvailable)
{
int size = networkStream.Read(buffer, 0, buffer.Length);
OnmessageEvent?.Invoke(buffer, _tcpClient);
}
}
}
catch (Exception ex)
{
Logger.Default.Error($"{MethodBase.GetCurrentMethod().DeclaringType.FullName} {ex.Message},{ex.StackTrace}", ex);
return;
}
}
/// <summary>
/// 完善接收消息的过程
/// 动态缓冲器大小接收.
/// </summary>
private void ReceiveMessageNew()
{
try
{
NetworkStream networkStream = _tcpClient.GetStream();
while (isConnected)
{
if (_tcpClient.Available > 0)//有数据
{
int bufferSize = _tcpClient.Available;//动态缓冲区大小
byte[] buffer = new byte[bufferSize];
if (networkStream.DataAvailable)//是否存在可读数据
{
int size = networkStream.Read(buffer, 0, buffer.Length);
OnmessageEvent?.Invoke(buffer, _tcpClient);
}
}
}
}
catch (Exception ex)
{
Logger.Default.Error($"{MethodBase.GetCurrentMethod().DeclaringType.FullName} {ex.Message},{ex.StackTrace}", ex);
return;
}
}
/// <summary>
/// 手动接收消息
/// </summary>
public byte[] ReceiveManual()
{
try
{
if (isConnected)//先确保连接
{
NetworkStream networkStream = _tcpClient.GetStream();
if (_tcpClient.Available>0)//有数据
{
int bufferSize = _tcpClient.Available;
byte[] buffer = new byte[bufferSize];
if (networkStream.DataAvailable)
{
int size = networkStream.Read(buffer, 0, buffer.Length);
OnmessageEvent?.Invoke(buffer, _tcpClient);
return buffer;
}
}
}
return null;
}
catch (Exception ex)
{
Logger.Default.Error($"{MethodBase.GetCurrentMethod().DeclaringType.FullName} {ex.Message},{ex.StackTrace}", ex);
return null;
}
}
}
}
SocketClient
于 2022-10-09 09:50:17 首次发布