本文主要介绍了C#以太网Sockets客户端设计实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
【1】客户端对象
using System.Net;// DNS_静态对象
using System.Net.Sockets;
// 字段位置
private Socket socket业务; //对象既可以当服务器,又可以当客户端
TcpListener tcpListener; //服务器对象
TcpClient tcpClient; //客户端对象
【2】初始化
Socket tcpClient客户端;
tcpClient客户端 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
【3】连接
#region 连接
/// <summary>
/// 建立连接
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="port">端口号</param>
public void Connect(string ip, string port)
{
try
{
//实例化Socket
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//设置Socket属性
tcpClient.SendTimeout = this.SendTimeOut;
tcpClient.ReceiveTimeout = this.ReceiveTimeOut;
//封装一个EndPoint对象
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
//建立连接
tcpClient.Connect(endPoint);
}
catch (Exception ex) { MessageBox.Show(ex.Message); }//显示错误
}
#endregion
【4】收发
#region 读取并接受
/// <summary>
/// 发送并接受
/// </summary>
/// <param name="SendByte"></param>
/// <returns></returns>
public byte[] SendAndReceive(byte[] SendByte)
{
try
{
if (tcpClient.Available >= 1)// 丢弃字节
{
#region 加载
byte[] buffer = new byte[tcpClient.Available];//准备加载
tcpClient.Receive(buffer, buffer.Length, SocketFlags.None);//开始加载
#endregion
}
#region 计时
//====现在时间======================================
str_发送后记时 = new StringBuilder(String.Format("{0,9}",
DateTime.Now.Second.ToString() + "s"
+ DateTime.Now.Millisecond.ToString() + "ms:")); //固定长度9 右对齐
#endregion
tcpClient.Send(SendByte);// 发送
#region 委托
if (Help_ModBus.Wt_set != null)
{
Help_ModBus.Wt_set(SendByte, str_发送后记时.ToString());
}
#endregion
return ReadMessage();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }//显示错误
finally
{
//InteractiveLock.Leave();
}
return null;
}
/// <summary>
/// 读取缓冲区值
/// </summary>
/// <returns></returns>
private byte[] ReadMessage()
{
DateTime startTime = DateTime.Now;//记录开始时间
do
{
if (tcpClient.Available >= 5 )// 字节
{
#region 计时
//====现在时间======================================
str_发送后记时 = new StringBuilder(String.Format("{0,9}",
DateTime.Now.Second.ToString() + "s"
+ DateTime.Now.Millisecond.ToString() + "ms:")); //固定长度9 右对齐
#endregion
#region 加载
byte[] buffer = new byte[tcpClient.Available];//准备加载
tcpClient.Receive(buffer, buffer.Length, SocketFlags.None);//开始加载
#endregion
#region 委托
if (Help_ModBus.Wt_get != null)//委托呼叫ui
{
Help_ModBus.Wt_get(buffer, str_发送后记时.ToString());// ui显示
}
#endregion
return buffer;
}
#region 超时跳出
if ((DateTime.Now - startTime).TotalMilliseconds > ReceiveTimeOut+500)// 超时 1.5s
{
break;// 已经超时
}
#endregion
} while (true);
return null; // 相当失败
//Thread.Sleep(ReceiveTimeOut);// 延时15ms
//int count = tcpClient.Available; // 字节
//if (count == 0)
//{
// return null;
/