class ModBusTcp : IDisposable
{
/// <summary>
/// 服务端IP地址 例:192.168.1.1
/// </summary>
public string IP = "192.168.1.1";
/// <summary>
/// 服务端端口号 例:ModBus默认502
/// </summary>
public int Port = 502;
/// <summary>
/// 超时时间
/// </summary>
public int TimeOut = 3;
//定义TCP套接字实例
private Socket socket = null;
//建立套接字连接
public void Connect()
{
//定义套接字类型和和协议
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//套接字超时设置
this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout,TimeOut);
//实例化网络端点
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(IP), Port);
//建立连接
this.socket.Connect(ip);
}
//套接字以字节数组形式发送数据
public void Send(byte[] values)
{
this.socket.Send(values);
}
//套接字以字节数组形式接收数据
public byte[] Receive()
{
//实例化接收数组
byte[] receiveData = new byte[255];
//接收数据,并返回接收字节数
int length = this.socket.Receive(receiveData);
byte[] result = new byte[length];//定义接收数据长度的数组
//复制,并返回接收数据
Array.Copy(receiveData, 0, result, 0, length);
// Dispose();
return result;
}
//是否已经建立连接
public bool isConn()
{
bool boolflage = false;
if (socket.Connected) boolflage = true;
return boolflage;
}

//销毁套接字,释放资源
public void Dispose()
{
//如果套接字连接连通,先禁止其收发,然后关闭
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
//回收套接字
if (socket != null)
{
socket = null;
}
}
}

相关文章:

  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2021-12-07
  • 2021-06-18
  • 2022-02-17
  • 2021-12-31
  • 2021-06-02
猜你喜欢
  • 2021-04-26
  • 2022-12-23
  • 2022-12-23
  • 2021-11-10
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案