字段:
Socket RJ45;//以太网
属性:
public Socket socket { get => RJ45; set => RJ45 = value; }
构造:
//实例化Socket
RJ45 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
连接:
//封装一个EndPoint对象 // ip地址,端口
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
try
{
//建立连接
RJ45.Connect(endPoint);
}
catch (Exception ex)
{
throw ex;
//MessageBox.Show(ex.Message);
}//显示错误
//catch (Exception ex) {throw ex; }//显示错误
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;// 获取主机相关信息
hostEntry = Dns.GetHostEntry(server);// 循环浏览AddressList以获得受支持的AddressFamily。这是为了避免
// 当主机IP地址与地址系列不兼容时发生的异常
// (通常在IPv6情况下)。
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
SET:
#region 只发送
/// <summary>
/// 只发送
/// </summary>
/// <param name="stringcmd"></param>
/// <returns></returns>
public int send(string stringcmd)
{
stringcmd.Replace(" ", "");//去除空白
byte[] buffer = StringsToHexBytes(stringcmd);//准备报文 //去除空白 StringsToHexBytes
try
{
RJ45.Send(buffer);// 发送
return 0;
}
catch (Exception ex)
{
throw ex;
}}
#endregion
PUT:
#region 发送并接收
/// <summary>
/// 发送并接受
/// </summary>
/// <param name="SendByte"></param>
/// <returns></returns>
public byte[] SendAndReceive(byte[] SendByte, string TXstr)
{
try
{
//丢弃字节
if (RJ45.Available != 0)// 丢弃字节
{
#region 加载
byte[] buffer = new byte[RJ45.Available];//准备加载
RJ45.Receive(buffer, buffer.Length, SocketFlags.None);//开始加载
#endregion
}
RJ45.Send(SendByte);// 发送
//====现在时间======================================
string ATtime = DateTime.Now.ToString("ss's'ffff:");#region 委托
if (Help_ModBus.Wt_set != null)
{
Help_ModBus.Wt_set(SendByte, ATtime + TXstr);
}
#endregionreturn ReadMessage();
}
catch (Exception ex)
{
throw ex;
//MessageBox.Show(ex.Message);
}//显示错误return null;
}/// <summary>
/// 读取缓冲区值
/// </summary>
/// <returns></returns>
private byte[] ReadMessage()
{
DateTime startTime = DateTime.Now;//记录开始时间
do
{
if (RJ45.Available >= 5)// 字节
{
#region 计时
//====现在时间======================================
ATtime = DateTime.Now.ToString("ss's'ffff:");
#endregion
#region 加载
byte[] buffer = new byte[RJ45.Available];//准备加载
RJ45.Receive(buffer, buffer.Length, SocketFlags.Peek);//开始加载
#endregion
#region 委托
if (Help_ModBus.Wt_get != null)//委托呼叫ui
{
Help_ModBus.Wt_get(buffer, ATtime);// ui显示
}
#endregion
return buffer;
}
#region 超时跳出
if ((DateTime.Now - startTime).TotalMilliseconds > ReceiveTimeOut + 1500)// 超时 ___ms
{
break;// 已经超时
}
#endregion} while (true);
return null; // 未应答//Thread.Sleep(ReceiveTimeOut);// 延时15ms
//int count = tcpClient.Available; // 字节
//if (count == 0)
//{
// return null;
//}
//else
//{
// byte[] buffer = new byte[count];
// tcpClient.Receive(buffer, count, SocketFlags.None);
// //byte[] buffer2 = Encoding.Default.GetBytes(str_发送后记时.ToString());
// byte[] buffer3 = { buffer2 , buffer };
// //return buffer2;
// #region 计时
// //====现在时间======================================
// str_发送后记时 = new StringBuilder(String.Format("{0,9}",
// DateTime.Now.Second.ToString() + "s"
// + DateTime.Now.Millisecond.ToString() + "ms:")); //固定长度9 右对齐
// #endregion
// if (Wt_get!=null)
// {
// Wt_get(buffer, str_发送后记时.ToString());
// }
// return buffer;
//}//==================================
//int count = tcpClient.Available;
//int cycletimer = 0;
//while (count == 0)
//{
// count = tcpClient.Available;
// cycletimer++;
// Thread.Sleep(20);
// if (cycletimer > MaxCycleTimer)
// {
// break;
// }
//}
//if (count == 0)
//{
// return null;
//}
//else
//{
// byte[] buffer = new byte[count];
// tcpClient.Receive(buffer, count, SocketFlags.None);
// return buffer;
//}
}
/// <summary>
/// 此方法请求指定服务器的主页内容。
/// int port = 80;
/// </summary>
/// <param name="server"></param>
/// <param name="port"></param>
/// <returns></returns>
public static string SocketSendReceive(string server, int port)
{
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
string page = "";// 使用指定的服务器和端口创建套接字连接。
using (Socket s = ConnectSocket(server, port))
{if (s == null)
return ("连接失败");// 向服务器发送请求。
s.Send(bytesSent, bytesSent.Length, 0);// 接收服务器主页内容。
int bytes = 0;
page = "Default HTML page on " + server + ":\r\n";// 以下内容将被阻止,直到页面被传输。
do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
}return page;
}#endregion
断开:
#region 断开
/// <summary>
/// 断开连接
/// </summary>
void DisConnect()
{
RJ45?.Close();
}#endregion