public class Memobus_TCP_Lib
{
//IPEndPoint PLC地址;
//IPEndPoint 本地地址 ;
Socket 套接字 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public byte 子站地址 { get; set; } = 0x01;//子控制器地址-定义成属性
public Memobus_TCP_Lib()
{
//PLC地址 = new IPEndPoint(0, 0);
//本地地址 = new IPEndPoint(0, 0);
}
/// <summary>
/// PLC连接Connect
/// </summary>
/// <param name="PLC_IP"></param>
/// <param name="PLC_端口"></param>
/// <param name="本地_IP"></param>
/// <param name="本地_端口"></param>
/// <returns>成功返回True,失败返回False</returns>
public bool _Connect(string PLC_IP, int PLC_端口, string 本地_IP, int 本地_端口)
{
try
{
//套接字 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (!套接字.Connected)
{
套接字 = null;
套接字 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
套接字.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress);
套接字.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
IPEndPoint PLC地址;
PLC地址 = null;
PLC地址 = new IPEndPoint(0, 0);
IPEndPoint 本地地址;
本地地址 = null;
本地地址 = new IPEndPoint(0, 0);
PLC地址.Address = IPAddress.Parse(PLC_IP);
PLC地址.Port = PLC_端口;
本地地址.Address = IPAddress.Parse(本地_IP);
本地地址.Port = 本地_端口;
if(套接字.Connected)
套接字.Disconnect(true);
套接字.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
if (!套接字.IsBound)
套接字.Bind(new IPEndPoint(IPAddress.Parse(本地_IP), 本地地址.Port));
System.Threading.Thread.Sleep(10);
套接字.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
套接字.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
//套接字.Connect(new IPEndPoint(IPAddress.Parse(PLC_IP), PLC地址.Port));
//改成异步连接
套接字.BeginConnect(new IPEndPoint(IPAddress.Parse(PLC_IP), PLC地址.Port), null, null);
return true;
}
catch (Exception e)
{
//Console.WriteLine(e);
return false;
}
}
/// <summary>
/// Socket断开连接
/// </summary>
public bool disConnect()//Socket断开连接
{
if (套接字 != null && 套接字.Connected)
{
套接字.Shutdown(SocketShutdown.Both);
System.Threading.Thread.Sleep(20);
//套接字.Close();
套接字.Disconnect(true);
套接字.Close();
套接字.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
}
return true;
//if (套接字 != null)
//{
// 套接字.Close();
//}
//return true;
}