欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# System.Net.Sockets =》TcpListener用法

程序员文章站 2022-03-22 14:21:27
开始运行 监听 处理事件 ......
 private tcplistener _listener;
#region 初始化 listener public override void init() { try { devinfo.read(); var localaddr = ipaddress.parse(ip); var port = convert.toint32(port); _listener = new tcplistener(localaddr, port); } finally { statuschangedevent?.invoke(status); } } #endregion

开始运行

        public override void start()
        {
            init();
            _listener?.start();
            task.factory.startnew(monittcpclientconnect);           
        }

监听

        private void monittcpclientconnect()
        {
            while (true)
            {
                try
                {
                    var client = _listener.accepttcpclient();
                    task.factory.startnew(monitorrecvdata, client);
                }
                catch
                {
                    _listener.stop();
                    _listener = null;                return;
                }
            }
        }

处理事件

        private void monitorrecvdata(object obj)
        {
            try
            {
                var tcpclient = obj as tcpclient;
                if (tcpclient == null)
                {
                    return;
                }

                var buffer = new byte[1024];var stream = tcpclient.getstream();
                while (true)
                {
                    var count = stream.read(buffer, 0, buffer.length);

                    if (count == 0)
                    {
                        throw new exception("客户端下线");
                    }

                    var str = encoding.ascii.getstring(buffer, 0, count);
                }
            }
            catch
            {
                // ignored
            }
        }