C# 网络编程 TcpListener

1.服务断代码

 public partial class Server : Form
    {

        private bool lk = true;

        public Server()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(textBox1.Text);

            TcpListener server = new TcpListener(ip, int.Parse(textBox2.Text));
            server.Start();

            TaskFactory tasks = new TaskFactory();
            string ipaddress = string.Empty;
            TcpClient client = null;
            while (lk)
            {
                Console.WriteLine("等待连接。。。");
                client = server.AcceptTcpClient();

                tasks.StartNew(() => HandleClient(client, ipaddress)).Wait();
            }
        }

        private void HandleClient(TcpClient tcpclient, string ipadd)
        {

            lock (tcpclient)
            {
                if (tcpclient == null)
                {
                    return;
                }

                // Buffer for reading data
                Byte[] bytes = new Byte[1024];
                String data = null;

                // Enter the listening loop.
                while (tcpclient.Connected)
                {


                    data = null;

                    NetworkStream stream = tcpclient.GetStream();

                    int i;

                    if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);

                        byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);

                        //stream.Write(msg, 0, msg.Length);
                        textBox3.AppendText(data);
                    }
                    tcpclient.Close();
                }
            }
        }

    }
View Code

相关文章:

  • 2022-12-23
  • 2022-01-20
  • 2021-12-14
  • 2021-10-18
  • 2021-12-14
  • 2021-11-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-03
  • 2021-07-06
  • 2021-08-19
  • 2022-12-23
相关资源
相似解决方案