[Socket Network Programming] Advanced Edition: Using Multithreading

introduction:

In computer programming , a basic concept is to control multiple tasks at the same time. Many programming problems require that the program stop what it is doing, handle some other problem, and then return to the main process . This can be achieved in a number of ways. The asynchronous synchronization of the Unity network is inseparable from the use of threads.

Table of contents

❤ Definition of thread:

Du Niang defined

 I defined

❤ Interactive test

❤Socket practical use:

Server

 1. Encapsulate the interactive server socket.

 2. Use threads to implement broadcast messages.

client 

strange! 

❤Source code sharing (it sucks, take a look if you don’t dislike it)


❤ Definition of thread:

Du Niang defined

1. Every program that is running on the system is a process . Each process contains one or more threads. A process may also be the dynamic execution of an entire program or part of a program. A thread is a collection of instructions , or special sections of a program, that can be executed independently within the program. It can also be understood as the context in which the code runs. So threads are basically lightweight processes that are responsible for performing multiple tasks within a single program. Usually the operating system is responsible for the scheduling and execution of multiple threads. Uploading...Reupload Cancel Multithreading

2. A thread is a single sequential flow of control in a program. Running multiple threads simultaneously in a single program to do different tasks is called multithreading.

3. The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, and each thread has its own execution stack and program counter as its execution context. Multithreading mainly It is to save CPU time and make full use of it, depending on the specific situation. The running of the thread needs to use the computer's memory resources and CPU .

 I defined

In fact, a thread is a class with its own ideas. After the program executes to it, there is no need to "wait for it to finish executing before executing the next line of statement" , and the next line of statement can be processed directly. Special case: When the statement executed by the sub-thread and the statement in the next line are both loop statements, there will be an alternate execution situation, referred to as "win-win", and the thread can only be said to be a "good guy". 

❤ Interactive test

❤Socket practical use:

PS: After completing the simple server and client framework, you can upgrade the "equipment"! 

Before that, let's review that among the Socket methods, bind(), accept(), receive(), etc. are all blocking methods, that is, they will not proceed to the next statement until they are not executed or executed successfully. (Isn't it selfish! doge).

Server

 1. Encapsulate the interactive server socket.

We first improve the encapsulation of receiving and sending messages on the server side, and make a special class for it: vipServer

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ServerPRO
{
    class vipServer
    {
        byte[] vs = new byte[4096];

        public Socket socket;
        public vipServer(Socket newSocket)
        {
            this.socket = newSocket;
            

        }
       
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="massage"></param>
        public void sendMassage(string massage)
        {           
                byte[] size = UTF8Encoding.UTF8.GetBytes(massage);
                socket.Send(size);
        }
        /// <summary>
        /// 接收消息
        /// </summary>
        public string receiveMassage()
        {

            while (true)
            {
                int size2 = socket.Receive(vs);
                string massage = Encoding.UTF8.GetString(vs, 0, size2);
                Console.WriteLine("有客户端:" + massage);
                return massage;
            }
        }
        
    }
}

 2. Use threads to implement broadcast messages.

In order to prevent the accept() method in the while loop from blocking the progress of the broadcast message, we encapsulate the broadcast message method, and then delegate it to the thread as an entry function , and then we can start the thread to broadcast the message unimpeded to all clients.

PS: The entry function of Threadstart can only be of void type

            
//用一个队列存储vipServer对象池

          List<vipServer> listvipServer=new List<vipServer>();

//运用子线程形成专属交互socket

            Socket newSocket = null;
            Thread thread = new Thread(new ThreadStart(broadcast));
            thread.Start();
            while (true)
            {
                newSocket = Server.Accept();


                if (newSocket != null)
                {
                    Console.WriteLine("{0}用户连接", newSocket);
                    vipServer withServer = new vipServer(newSocket);
                    listvipSocket.Add(withServer);
                    newSocket = null;

                }
                
                

            }
        //广播消息      
        void broadcast()
        {
                
                string massage = null;
                while (true)
                {
                    if (massage == null)
                    {
                        for (int i = 0; i < listvipSocket.Count; i++)
                        {
                            if (listvipSocket[i].socket != null)
                                massage = listvipSocket[i].receiveMassage();
                        }
                    }
                    if (massage != null)
                    {
                        for (int i = 0; i < listvipSocket.Count; i++)
                        {
                            listvipSocket[i].sendMassage(massage);
                            massage = null;

                        }
                    }
                }

            }

        }

client 

strange! 

The perfection of the client is actually similar to that of the server, and I just accept messages from the client without affecting the sending of messages. Here I did not thread the sending of messages, and the execution is weird! try it yourself

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Client
{
    class Program
    {
        static void Main()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 6060);
            Console.WriteLine("连接服务器成功...");

            byte[] sizeClient = new byte[4096];

            //接收消息的子线程
            Thread thread = new Thread(new ThreadStart(receiveMassage));
            thread.Start();
            

            string a = Console.ReadLine();
                //发送一次消息实验
            sendMassage(clientSocket, a);

            void receiveMassage()
            {
                while (true)
                {
                    int count = clientSocket.Receive(sizeClient);
                    string massage = Encoding.UTF8.GetString(sizeClient, 0, count);
                    Console.WriteLine("消息:" + massage);
                }
                
            }

        }

        /// <summary>
        /// 客户端的发送方法
        /// </summary>
        /// <param name="client"></param>
        /// <param name="abc"></param>
        public static void sendMassage(Socket client,string abc)
        {

            byte[] massageByte = Encoding.UTF8.GetBytes(abc);
            client.Send(massageByte);
        }
    }
}

❤Source code sharing (it sucks, take a look if you don’t dislike it)

 Github: https://github.com/PangZaiPeiZhu/ServerPRO.git

Guess you like

Origin blog.csdn.net/m0_64810555/article/details/126064910