该实例能异步读取网口数据,同时过滤掉犹豫异步读取导致的读取重复数据的问题,同时提供读取数据的十六进制转换方法
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
namespace zk.Client.HouHua
{
public sealed class SocketClient
{
/// <summary>
/// 连接服务器IP地址
/// </summary>
public string Ip { get; set; }
/// <summary>
/// 连接服务器端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 客户端连接状态
/// </summary>
public bool IsConnected { get; set; }
/// <summary>
/// 定义接收字符串数组的长度
/// </summary>
private static int _recByteArrayLength=1024;
public int RecByteArrayLength
{
get { return _recByteArrayLength; }
set { _recByteArrayLength = value; }
}
/// <summary>
/// 协议起始码
/// </summary>
private string _protocolHead="AA55";
public string ProtocolHead
{
get { return _protocolHead; }
set { _protocolHead = value; }
}
/// <summary>
/// 协议截止码
/// </summary>
private string _protocolEnd="ABBA";
public string ProtocolEnd
{
get { return _protocolEnd; }
set { _protocolEnd = value; }
}
private byte[] buffer = new byte[_recByteArrayLength];
private string oldbufferStr = string.Empty;//TCP读取数据缓存
public Socket client = null;//Socket实例声明
private IPAddress ipaddress = null;
private IPEndPoint ipendpoint = null;
/// <summary>
/// 客户端连接服务器端
/// </summary>
/// <returns></returns>
public bool ClientConnectServer()
{
if (client == null)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
if (ipaddress == null)
{
ipaddress = IPAddress.Parse(Ip);
}
if (ipendpoint == null)
{
ipendpoint = new IPEndPoint(ipaddress, Port);
}
try
{
if (!client.Connected)
{
client.Connect(ipendpoint);
}
}
catch (Exception ex)
{
ipendpoint = new IPEndPoint(ipaddress, Port);
client.BeginConnect(ipendpoint, new AsyncCallback(connectCallback), client);
}
return IsConnected = client.Connected;
}
/// <summary>
/// 关闭连接
/// </summary>
/// <returns></returns>
public bool CloseClient()
{
if (client == null)
{
return IsConnected = false;
}
try
{
if (client.Connected)
{
client.Close();
}
}
catch (Exception)
{
}
finally
{
IsConnected = client.Connected;
client.Dispose();
}
if (client != null)
{
client = null; ;
}
if (ipaddress != null)
{
ipaddress = null;
}
if (ipendpoint != null)
{
ipendpoint = null;
}
return true;
}
/// <summary>
/// 异步读取Tcp数据回调函数
/// </summary>
/// <param name="ar">异步操作的状态实例</param>
public void ReadCallback(IAsyncResult ar)
{
try
{
String content = String.Empty;
int bytesRead = client.EndReceive(ar); //结束挂起的异步读取并返回收到的字节数
if (bytesRead > 0)//大于零执行异步读取操作,读取数据
{
client.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReadCallback), client);////异步读取TCP数据
}
}
catch (Exception)
{
}
}
/// <summary>
/// 异步连接端口
/// </summary>
/// <param name="ar">异步操作的状态实例</param>
private void connectCallback(IAsyncResult ar)
{
try
{
client.EndConnect(ar);//结束挂起的异步连接请求。
client.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReadCallback), client);////异步连接端口
}
catch (Exception)
{
}
}
/// <summary>
/// 读TcpClent数据
/// </summary>
/// <param name="readByte">输出数据字节</param>
/// <returns>0:数据正确输出;-1网络链路不同;-2:不符合指定协议头尾格式;-3:读取的重复缓存数据;-8:未知错误</returns>
public int ReadSocketByte(out Byte[] readByte)
{
int tag = 0;
readByte = new byte[_recByteArrayLength];
try
{
if (!client.Connected)//判断TCPClient是否处于连接状态,如果断开执行连接操作,同时输出显示
{
ClientConnectServer();//连接TCP
IsConnected = client.Connected;//Tcp连接状态标志位
if (!IsConnected)
{
return tag = -1;//-1链路不通
}
}
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client);//异步读取TCP数据
string strShow = ByteToString(buffer);//byte数组转换成十六进制字符串
//通过正则判断是否符合回示协议格式
Regex myRe = new Regex(string.Format(@"{0}(.*){1}", _protocolHead, _protocolEnd), RegexOptions.IgnoreCase);//正则表达式
string strmr = myRe.Match(strShow).ToString();
if (!myRe.IsMatch(strShow))//
{
return tag = -2;//-2协议头尾格式错误
}
if (oldbufferStr != strmr)
{
readByte = buffer;
oldbufferStr = strmr;
}
else
{
readByte = buffer;
oldbufferStr = strmr;
tag = -3;//-3重复数据
}
}
catch (Exception)
{
tag = -8;//未知错误
}
return tag;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="senddata">需要发送的十六进制字符串</param>
/// <returns>0:数据正确发送;-1网络链路不通;-8:未知错误</returns>
public int SendData(string senddata)
{
int tag = 0;
try
{
if (!client.Connected)//判断TCPClient是否处于连接状态,如果断开执行连接操作,同时输出显示
{
ClientConnectServer();//连接TCP
IsConnected = client.Connected;//Tcp连接状态标志位
if (!IsConnected)
{
return tag = -1;//-1链路不通
}
}
byte[] sendByte = HexToByte(senddata);
client.Send(sendByte);
}
catch (Exception)
{
tag = -8;
}
return tag;
}
/// <summary>
/// byte数组转HEX字符串
/// </summary>
/// <param name="InBytes"></param>
/// <returns></returns>
public string ByteToString(byte[] InBytes)
{
string StringOut = "";
foreach (byte InByte in InBytes)
{
StringOut = StringOut String.Format("{0:X2}", InByte);
}
return StringOut;
}
/// <summary>
/// HEX字符串转byte数组
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public byte[] HexToByte(string msg)
{
msg = msg.Replace(" ", "");//移除空格
byte[] comBuffer = new byte[msg.Length / 2];
for (int i = 0; i < msg.Length; i = 2)
{
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
}
return comBuffer;
}
}
}
评论