socket related

        private void btn_start_Click(object sender, EventArgs e)
        {
            // Socket server-side logic
             // 1. Create a socket object (for server-side monitoring)
             // para1: use the ipv4 network addressing protocol.
            // para2: data transmission mode stream protocol.
             // para3: setting of communication protocol (tcp protocol) 
            Socket serverSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             // 2. Bind IP and port 
            IPAddress ip = IPAddress.Parse( "" ); // Convert string to IP address 
            IPEndPoint ipendPoint = new IPEndPoint(ip, int .Parse( "" )); // Give port number 
            serverSoc.Bind(ipendPoint );

            // 3. Enable listening 
            serverSoc.Listen( 10 ); // The maximum length of the pending queue. After this number is exceeded, the oldest will be deleted
             // 4. Start accepting client connections


            ThreadPool.QueueUserWorkItem(new WaitCallback(this.SartAcceptClient), serverSoc);
        }
        public  void SartAcceptClient( object state)
        {
            var serverSoc = (Socket)state;
            while (true)
            {
                Socket proxSocket = serverSoc.Accept(); // Once the accept method is executed, the current thread is blocked. Waiting for the client to connect.
                // Convert string to byte array 
                byte [] data = Encoding.Default.GetBytes( " Hello World " );
                proxSocket.Send(data, 0 , data.Length, SocketFlags.None); // The last parameter, when accessing in the same local area network, use None, if it is external network access, then you need to set other parameters
                 // proxSocket.Shutdown(SocketShutdown.Both); // Close the socket object on the server side. Send a 0-byte message to inform the other party that the communication is over.
                // proxSocket.Close();
                 // serverSoc.Close(); 
            }            
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325235245&siteId=291194637