• socket tcp 通讯 示例


            private void button1_Click(object sender, EventArgs e)
            {
                Socket srv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8080);
                srv.Bind(ep);
                srv.Listen(100);

                Thread th = new Thread(new ParameterizedThreadStart(GetConnection));
                th.IsBackground = true;
                th.Start(srv);

                button1.Enabled = false;
            }

            private void GetConnection(object _srv)
            {
                Socket srv = (Socket)_srv;
                while (true)
                {
                    Socket client = srv.Accept();

                    Thread th = new Thread(new ParameterizedThreadStart(GetMesFromClient));
                    th.IsBackground = true;
                    th.Start(client);
                }

            }

            private void GetMesFromClient(object _client)
            {
                Socket client = (Socket)_client;
                while (true)
                {
                    byte[] tmp = new byte[1024];
                    int len = client.Receive(tmp);
                    if (len == 0)
                        break;

                    byte[] buffer = new byte[len];
                    Array.Copy(tmp, buffer, len);

                    string mes = Encoding.Default.GetString(buffer);
                    int hd = client.Handle.ToInt32();
                }

                if (client != null)
                {
                    client.Close();
                }
            }
  • 相关阅读:
    第二阶段冲刺7
    第二阶段冲刺6
    课后作业02需求分析
    阅读计划
    个人总结
    第十六周学习进度条
    第十五周学习进度条
    《梦断代码》阅读笔记03
    《梦断代码》阅读笔记02
    《梦断代码》阅读笔记01
  • 原文地址:https://www.cnblogs.com/bloodofhero/p/2569401.html
Copyright © 2020-2023  润新知