• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#tcpudp串口通信

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

简单的实现tcp同步和异步,udp,串口通信

static List<TcpClientState> clientArray = new List<TcpClientState>();
        static void AsyncTCP(IPEndPoint iep)
        {
            TcpListener listener = new TcpListener(iep);
            listener.Start();
            byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };
            listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null);
            #region//异步tcp
            AsyncCallback dataReceiveAsyncCallback = null;
            dataReceiveAsyncCallback = ar =>
            {
                TcpClientState innerclient = (TcpClientState)ar.AsyncState;
                if ((innerclient.InnerClient == null) || (!innerclient.InnerClient.Connected))
                    return;
                NetworkStream stream = innerclient.InnerClient.GetStream();
                int num;
                //异常断开
                try { num = stream.EndRead(ar); }
                catch { num = 0; }

                if (num < 1)//断开连接
                {
                    Console.WriteLine(innerclient.InnerClient.Client.RemoteEndPoint.ToString() + "断开连接");
                    clientArray.Remove(innerclient);
                    return;
                }

                byte[] receivebytes = new byte[num];
                Buffer.BlockCopy(innerclient.Buffer, 0, receivebytes, 0, num);
                string s = Encoding.Default.GetString(receivebytes);
                Console.WriteLine(s);
                var data = Encoding.Default.GetBytes(string.Format("收到:{0}", s));
                innerclient.InnerClient.GetStream().BeginWrite(data, 0, data.Length,
                    arw =>
                    {
                       ((TcpClient)arw.AsyncState).GetStream().EndWrite(arw);
                    },innerclient.InnerClient);
                stream.BeginRead(innerclient.Buffer, 0, innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient);
            };

            AsyncCallback connectAsyncCallbackcallback = null;
            connectAsyncCallbackcallback = ar =>
            {
                var listen = (TcpListener)ar.AsyncState;
                TcpClient client = listen.EndAcceptTcpClient(ar);
                Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功");
                byte[] buf = new byte[client.ReceiveBufferSize];
                TcpClientState innerclient = new TcpClientState(client, buf);
                clientArray.Add(innerclient);
                NetworkStream netstream = client.GetStream();
                netstream.BeginRead(innerclient.Buffer, 0, innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient);
                if (connectAsyncCallbackcallback == null) return;
                listen.BeginAcceptTcpClient(connectAsyncCallbackcallback, ar.AsyncState);
            };
            listener.BeginAcceptTcpClient(connectAsyncCallbackcallback, listener);
            Console.WriteLine("开始监听");
            Console.Read();

            #endregion
        }
        static void synctcp(IPEndPoint iep)
        {
            TcpListener listener = new TcpListener(iep);
            Console.WriteLine("开始监听");
            listener.Start();
            byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };
            listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null);

            #region //同步tcp
            Thread listenThread = new Thread(() =>
            {
                while (true)
                {
                    var client = listener.AcceptTcpClient();
                    Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功");
                    Thread datareceiveThread = new Thread(() =>
                    {
                        NetworkStream stream = client.GetStream();

                        while (true)
                        {
                            if (stream.DataAvailable)
                            {
                                byte[] buf = new byte[client.Client.ReceiveBufferSize];
                                int len = client.Client.Receive(buf);
                                Console.WriteLine(Encoding.Default.GetString(buf, 0, len));
                            }

                        }
                    });
                    datareceiveThread.Start();
                }
            });
            listenThread.Start();
            #endregion  
        }
        static void udp(IPEndPoint iep)
        {
            Socket udpSocket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            udpSocket.Bind(iep);
            var remotEndPoint = new IPEndPoint(IPAddress.Parse("10.6.179.44"), 10000);
           
            Thread thread=new Thread(() =>
            {
                while (true)
                {
                    if (udpSocket.Available > 0)
                    {

                        byte[] buf = new byte[udpSocket.Available];
                        udpSocket.Receive(buf);
                        Console.WriteLine(Encoding.Default.GetString(buf));
                        udpSocket.SendTo(buf, remotEndPoint);
                    }
                  
                }
            });
            thread.Start();
            Console.WriteLine("wait");
            Console.Read();
        }

        static void com(string com, int port)
        {
            var m_port = new SerialPort(com, port);
          
            m_port.DataReceived += (obj, args) =>
            {
                int length = m_port.ReadBufferSize;
                byte[] buf = new byte[length];
                m_port.Read(buf, 0, length);
                string s = Encoding.Default.GetString(buf);
                Console.WriteLine(s);
                m_port.Write(buf, 0, buf.Length);
            
            };
            m_port.Open();
        }

 tcp异步客户端

        /// <summary> 连接服务端
        /// </summary>
        /// <param name="ip">服务端IP</param>
        /// <param name="port">服务端端口</param>
        static void AsynConnect(string ip, int port)
        {
            var serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            var _client=new TcpClient();
            _client.BeginConnect(serverEndPoint.Address, serverEndPoint.Port, asynresult =>
            {
                _client.EndConnect(asynresult);
                Console.WriteLine("连上服务端{0}", _client.Connected);
                if (_client.Connected)
                {
                    NetworkStream stream = _client.GetStream();
                    byte[] buf = new byte[_client.ReceiveBufferSize];
                    AsyncCallback asyncCallback = null;
                    asyncCallback = asynreadresult =>
                    {
                        int num = 0;
                        try
                        {
                             num = stream.EndRead(asynreadresult);
                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            num = 0;
                        }
                        if (num == 0)
                        {
                            Console.WriteLine("服务端断开");
                            return;
                        }
                        byte[] receivebytes = new byte[num];
                        Buffer.BlockCopy(buf, 0, receivebytes, 0, num);
                        Console.WriteLine(Encoding.Default.GetString(receivebytes));
                        stream.BeginWrite(receivebytes, 0, receivebytes.Length, result =>
                        {
                            stream.EndRead(result);
                        }, null);

                        stream.BeginRead(buf, 0, buf.Length, asyncCallback, null);
                    };
                    stream.BeginRead(buf, 0, buf.Length, asyncCallback, null);
                }

            }, _client);

            Console.Read();
        }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap