C#以太网Sockets客户端设计

参数参考:

C#以太网Sockets服务器设计_cfqq1989的博客-CSDN博客_c# 以太网

【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;
            //}
            //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;
            //}
        }
        #endregion

【5】断开

 #region 断开
        /// <summary>
        /// 断开连接
        /// </summary>
        public void DisConnect()
        {
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
        }

        #endregion

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值