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

0
10
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
            }
        }

<

发布回复

请输入评论!
请输入你的名字