C#TCP+接收线程

private static void CreatTCP()
{
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_Socket.Bind(new IPEndPoint(m_UpdReceiveDataIP, 6022));
m_Socket.Listen(20);

        m_TCPReceiveDataID = new Thread(TcpReceiveData);
        m_TCPReceiveDataID.IsBackground = true;
        m_TCPReceiveDataID.Start();
    }
private static void TcpReceiveData()
    {
        Socket connection = null;
        while (m_IsTCPSendN)
        {
            connection= m_Socket.Accept();
            byte[] senddes = Encoding.UTF8.GetBytes("n");
            connection.Send(senddes);
            byte[] idrec = new byte[1024 * 1024];
            int length = connection.Receive(idrec);
            string m_cID = Encoding.UTF8.GetString(idrec, 0, length);
            if (m_cID == 123)
            {
                m_IsTCPSendN = false;

                ExitApplication();
            }
            else
            {
                Thread.Sleep(5000);
                byte[] senddesn = Encoding.UTF8.GetBytes("n");
                m_Socket.Send(senddesn);
            }
        }
    }

 private static void ExitApplication()
    {
        Console.WriteLine("将在" + m_TimerExit + "后关闭");
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        while (true)
        {
            if (stopwatch.Elapsed.Seconds >= 10)
            {
                Process[] process = Process.GetProcessesByName("DisposeIP");
                foreach (Process p in process)
                {
                    if (!p.HasExited)  // 如果程序没有关闭,结束程序
                    {
                        WaitForCloseProcess(p);
                        break;
                    }
                }
            }
        }
    }

private static void WaitForCloseProcess(Process p)
{
try
{
p.Kill();
p.WaitForExit();
}
catch (System.ComponentModel.Win32Exception e)
{
Console.WriteLine (“终止进程“” + p.ProcessName + “”异常”, e.Message);
}
catch (NotSupportedException e)
{
Console.WriteLine(“终止进程“” + p.ProcessName + “”异常”, e.Message);
}
catch (InvalidOperationException)
{
return;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值