C System. Net. Sockets = TcpListener usage

Time:2019-10-4
Private TcpListener_listener;#region initialization 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

Start running

        public override void Start()
        {
            Init();
            _listener?.Start();
            Task.Factory.StartNew(MonitTcpClientConnect);           
        }

Monitor

        private void MonitTcpClientConnect()
        {
            while (true)
            {
                try
                {
                    var client = _listener.AcceptTcpClient();
                    Task.Factory.StartNew(MonitorRecvData, client);
                }
                catch
                {
                    _listener.Stop();
                    _listener = null;                return;
                }
            }
        }

Handling events

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 ("client offline");
                    }

                    var str = Encoding.ASCII.GetString(buffer, 0, count);
                }
            }
            catch
            {
                // ignored
            }
        }

 

Recommended Today

Introduction and overview of NoSQL

1.1 INTRODUCTION1.1.1 1 under the background of Internet era, why do you use nosql1 single machine MySQL In the 1990s, the number of visitors to a website was generally small, and it could be easily handled with a single database. At that time, there were more static web pages and less dynamic interactive websites. Under […]