C Socket network programming example

  • 2020-12-16 06:04:39
  • OfStack

This article gives an example of C# Socket network programming techniques. Share to everybody for everybody reference. The specific analysis is as follows:

The client wants to connect to the server: First, know the server's IP address. There are many applications on the server, and each application has one port number
So a client wanting to communicate with an application in the server must know the IP address of that application's server and the port number for that application

TCP protocol: secure and stable, generally no data loss, but low efficiency. Using TCP to generate data 1, 3 handshakes (low efficiency, 3 handshakes by myself)

UDP protocol: fast, efficient, but unstable and prone to data loss (without three handshakes, no matter whether the server is free or not, all the information will be sent to the server with all the efficiency. But when the server is busy, it cannot process your data, which will easily cause data loss and instability)

using System;  
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net.Sockets; 
using System.Net; 
using System.Threading; 
namespace Socket communication  

    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
            this.txtPort.Text = "5000"; 
            this.txtIp.Text = "192.168.137.1"; 
        } 
        private void btnStart_Click(object sender, EventArgs e) 
        { 
            // Create on the server side when you click Start listening 1 One in charge of listening IP Address and port number Socket 
            Socket socketWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 
            //Any: provide 1 a IP Address indicating that the server should listen for client activity on all network interfaces. This field is read-only.  
            IPAddress ip = IPAddress.Any; 
            // Create port number object; will txtPort.Text The value of the control is set to the server-side port number  
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)); 
            // Listening to the  
            socketWatch.Bind(point); 
            ShowMsg(" Listening to success "); 
            socketWatch.Listen(10);// The maximum length of the connection queue ; That is: 1 A maximum of several clients can be connected in a time point, beyond the length of the queue  
            // Wait for the client to connect ;Accept() This method accepts a client connection and creates a new connection 1 Someone in charge of correspondence Socket 
            Thread th = new Thread(Listen); // If the method executed by the thread has parameters , The parameter must be object type  
            Control.CheckForIllegalCrossThreadCalls = false; // because .net Cross-thread access is not allowed, so cross-thread checking is cancelled here. .net Without checking if there is cross-thread access, all will not report: "Never create controls." txtLog "Thread to access it" This error enables cross-thread access  
            th.IsBackground = true; // will th This thread is set to background thread.  
            //Start(object parameter); parameter:1 Object containing the data to be used by the method executed by the thread , That is thread execution Listen Method, Listen The parameters of the  
            th.Start(socketWatch);  // The argument in parentheses is actually Listen() Method parameters. because Thread th = new Thread(Listen) You can only write the method name in parentheses ( The function name ) but Listen() Methods have parameters, so use them Start() Method adds its arguments to it  
        } 
        /// <summary> 
        /// Wait for a client connection, and create it if you detect a client connection coming in 1 Three that correspond with it Socket 
        /// </summary> 
        /// <param name="o"></param> 
        void Listen(object o) // Why don't you just pass it on here Socket What about parameters of type? The reason is that the method being executed by the thread has arguments , The parameter must be object type  
        { 
            Socket socketWatch = o as Socket; 
            while (true) // Why is there one here while Cycle? Because when 1 A personal connection creates a communication with it when it comes in Socket After the program will be executed down, will not come back for the first 2 Personal connection creation responsible for communication Socket . It should be everyone ( Each client ) create 1 Three that correspond with it Socket ) so write it in the loop.  
            { 
                // Wait for the client to connect ;Accept() This method accepts a client connection and creates a new connection 1 Someone in charge of correspondence Socket 
                Socket socketSend = socketWatch.Accept(); 
                dic.Add(socketSend.RemoteEndPoint.ToString(), socketSend); // (According to the client IP Address and port number of the person responsible for the communication Socket , for each client 1 Someone in charge of correspondence Socket ), ip The address and port number are the keys that will be responsible for the communication Socket As a value to dic Key value pair.  
                // We did it through this guy who was in charge of the correspondence socketSend The object's 1 a RemoteEndPoint Property, which allows you to access clients that are connected remotely Ip Address and port number  
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + " The connection is successful ");// Effect: 192.168.1.32: The connection is successful  
                comboBox1.Items.Add(socketSend.RemoteEndPoint.ToString()); // Add each client that you connect to combBox In the controls.  
                // After a successful client connection, the server should receive a message from the client.   
                Thread getdata = new Thread(GetData); 
                getdata.IsBackground = true; 
                getdata.Start(socketSend); 
            } 
        } 
        Dictionary<string, Socket> dic = new Dictionary<string, Socket>(); 
        /// <summary> 
        /// Constantly receiving messages from clients  
        /// </summary> 
        /// <param name="o"></param> 
        void GetData(object o) 
        { 
            while (true) 
            { 
                Socket socketSend = o as Socket; 
                // Put the data sent from the client first 1 Go into a byte array  
                byte[] buffer = new byte[1024 * 1024 * 2]; // create 1 The length of the byte array is 2M 
                // The actual number of valid bytes received ; ( using Receive Method receives data from the client and saves the data to buffer In the byte array, returns 1 The length of the received data ) 
                int r = socketSend.Receive(buffer); 
                if (r == 0) // If the number of valid bytes received is 0 Indicates that the client is closed. That's when you break out of the loop.  
                { 
                    // Only the client sends messages to the user, not to the user 0 Bytes of length. Even if an empty message is sent, the empty message has a length. The length of all valid bytes received is 0 That means the client is closed  
                    break; 
                } 
                // will buffer The data in this byte array is as follows UTF8 To be decoded into something we can read string Type, because buffer The actual length of the data stored in this array is r a , so from index is 0 Bytes begin decoding, total decoding r Bytes long.  
                string str = Encoding.UTF8.GetString(buffer, 0, r); 
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str); 
            } 
        } 
        private void ShowMsg(string str) 
        { 
            txtLog.AppendText(str + "\r\n"); // will str This string is added to txtLog In this text box.  
        } 
        /// <summary> 
        /// The server sends a message to the client  
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void btnSend_Click_1(object sender, EventArgs e) 
        { 
            if (comboBox1.SelectedItem == null) // if comboBox Control has no selected value. The user is prompted to select the client  
            { 
                MessageBox.Show(" Please select the client "); 
                return; 
            } 
            string str = txtMes.Text; // Gets what the user enters (Information that the server wants to send to the client)  
            byte[] strByte = Encoding.Default.GetBytes(str); // Convert the information to 2 Hexadecimal byte array  
            string getIp = comboBox1.SelectedItem as string; //comboBox The storage is for the client ( ip+ Port number)  
            Socket socketSend = dic[getIp] as Socket; // According to this ( ip And port number) to go dic Find the corresponding key value pair Assigned to communicate with the client Socket Every client has it 1 One responsible for communicating with it Socket 】  
            socketSend.Send(strByte); // Send the information to the client  
        } 
    } 
}

cmd telnet 10.18.16.46 5000 is the port number of telnet server ip address binding

Hopefully this article has helped you with your C# programming.


Related articles: