实例介绍
【实例简介】
该实例能异步读取网口数据,同时过滤掉犹豫异步读取导致的读取重复数据的问题,同时提供读取数据的十六进制转换方法
【实例截图】【核心代码】
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;
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论