c# - 从所有套接字接收消息而不循环遍历所有套接字

标签 c# tcp tcplistener tcpsocket

我正在为我的 a 级项目使用 C# 和 unity 编写消息传递应用程序,它使用的是 tcp 客户端-服务器模型。我已经创建了一个可以接收消息的套接字列表,但我必须指定从中接收消息的套接字,当我只有 1 个客户端时这很适合测试,但我需要能够处理更多连接和循环通过每个套接字尝试从中接收消息似乎非常低效和缓慢。

我的问题是:如何在不使用上述方法的情况下接收来自多个客户端的消息?

我将发布特定部分,然后是完整代码,以便您了解我在做什么。

这是处理从套接字接收数据的线程

    public static void Thread1()
    {
        for (int i = 0; i <= 2; i++)
        {
            byte[] b = new byte[155];
            ///////// I need to specify the socket to receive from////////
            int k = counter.numbers1[counter.i2].Receive(b);
            //////////////////////////////////////////////////////////////
            string k1 = "";

            for (int i3 = 0; i3 < k; i3++)
                k1 = k1 + Convert.ToChar(b[i3]);

            Console.WriteLine(k1);

            string sender_endpoint = k1.Substring(0, 21); ;
            string receiver_endpoint = k1.Substring(22, 21);
            string message = k1.Substring(44, 100);
            string msgtype = k1.Substring(145, 1);
            Console.WriteLine(k1.Length);
            Console.WriteLine(sender_endpoint);
            Console.WriteLine(receiver_endpoint);
            Console.WriteLine(message);
            Console.WriteLine(msgtype);

            if (msgtype == "0") //message
            {
                Console.WriteLine("000");
            }
            else if (msgtype == "1") //command
            {
                Console.WriteLine("111");
            }
        }
    }

完整的服务器代码是:

namespace server
{
    static class counter
    {
        public static int i2 = 0;//main listener
        public static int i4 = 0;//port number
        public static List<TcpListener> numbers = new List<TcpListener>();//listeners
        public static List<Socket> numbers1 = new List<Socket>();//sockets
    }

    class server_code
    {
        public static void Main()
        {
            string xyz123 = "x";
            Thread thread3 = new Thread(new ThreadStart(Thread3));
            Thread test_thread = new Thread(() => Test_Thread (xyz123));
            thread3.Start();
        }

        public static void Thread1()
        {
            //message reactions
            for (int i = 0; i <= 2; i++)
            {
                byte[] b = new byte[155];
                int k = counter.numbers1[counter.i2].Receive(b);
                string k1 = "";

                for (int i3 = 0; i3 < k; i3++)
                    k1 = k1 + Convert.ToChar(b[i3]);

                Console.WriteLine(k1);

                string sender_endpoint = k1.Substring(0, 21); ;
                string receiver_endpoint = k1.Substring(22, 21);
                string message = k1.Substring(44, 100);
                string msgtype = k1.Substring(145, 1);
                Console.WriteLine(k1.Length);
                Console.WriteLine(sender_endpoint);
                Console.WriteLine(receiver_endpoint);
                Console.WriteLine(message);
                Console.WriteLine(msgtype);

                if (msgtype == "0") //message
                {
                    Console.WriteLine("000");
                }
                else if (msgtype == "1") //command
                {
                    Console.WriteLine("111");
                }
            }
        }

        public static void Thread2()
        {
            //client message receiver
            var host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    IPAddress ipAd = IPAddress.Parse(ip.ToString());

                    counter.numbers.Add(null); 
                    counter.numbers1.Add(null);

                    Console.WriteLine("");

                    Socket xyz1 = counter.numbers[counter.i2].AcceptSocket();

                    counter.numbers1[counter.i2] = xyz1;
                    ASCIIEncoding asen = new ASCIIEncoding();
                    counter.numbers1[counter.i2].Send(asen.GetBytes(counter.numbers1[counter.i2].RemoteEndPoint.ToString()));
                    Console.WriteLine("Connection accepted from " + counter.numbers1[counter.i2].RemoteEndPoint);
                    Console.WriteLine("connecting to " + counter.numbers[counter.i2].LocalEndpoint);
                    //System.Threading.Thread.Sleep(3000);

                    Thread thread1 = new Thread(new ThreadStart(Thread1));
                    thread1.Start();
                }
            }
        }

        public static void Thread3()
        {
            //new clients acception
            var host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    for (int i = 0; i <= 10; i++)
                    {
                        Console.WriteLine(ip.ToString());
                        IPAddress ipAd = IPAddress.Parse(ip.ToString());
                        TcpListener myList = new TcpListener(ipAd, 8080);
                        myList.Start();
                        Console.WriteLine("The local endpoint is  :" + myList.LocalEndpoint);

                        Socket s = myList.AcceptSocket();//////////////////////////////////////////////
                        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
                        Console.WriteLine("connecting to " + myList.LocalEndpoint);
                        ASCIIEncoding asen = new ASCIIEncoding();
                        counter.i2 = counter.i2 + i;
                        int portno = 8000;
                        s.Send(asen.GetBytes(portno.ToString()));

                        Console.WriteLine();
                        myList.Stop();
                        s.Close();
                        Thread thread2 = new Thread(new ThreadStart(Thread2));

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        counter.numbers.Add(null);

                        TcpListener xyz = new TcpListener(ipAd, portno);

                        counter.numbers[counter.i2] = xyz;
                        //Console.WriteLine(counter.i4);//current portno

                        counter.numbers[counter.i2].Start();
                        Console.WriteLine("The local End point is  :" + counter.numbers[counter.i2].LocalEndpoint);
                        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        thread2.Start();
                    }
                }
            }
        }
}

完整的客户端代码是:

public class cc : MonoBehaviour 
{
    public InputField NameField;
    private string x;
    private string y = "";
    //private int z = 0;

    static class ipadressnumber{
        public static string ipadressno = "192.168.1.250";
    }

    public void Start(){
            TcpClient tcpclnt = new TcpClient();

            tcpclnt.Connect(ipadressnumber.ipadressno,8080);
            Stream stm = tcpclnt.GetStream();

            byte[] bb=new byte[100];
            int k=stm.Read(bb,0,100);

            for (int i=0;i<k;i++){
                y = y + Convert.ToChar(bb[i]);
            }
            //Debug.Log(y);
            tcpclnt.Close();
    }

    public void OnSubmit() 
    {
        x =  NameField.text;
        //Debug.Log(x);

        try 
        {
            System.Net.IPAddress ipad = IPAddress.Parse(ipadressnumber.ipadressno);
            IPEndPoint ipLocalEndPoint = new IPEndPoint(ipad,8888);
            //TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
            TcpClient tcpclnt1 = new TcpClient();
            //Debug.Log(y);
            tcpclnt1.Connect(ipadressnumber.ipadressno,int.Parse(y));
            Stream stm = tcpclnt1.GetStream();

            byte[] bb=new byte[100];
            int k=stm.Read(bb,0,100);
            string lclep = "";

            for (int i=0;i<k;i++) 
            {
                lclep = lclep + Convert.ToChar(bb[i]);
            }

            String str=x;
            ////////////format of message:(sender endpoint, recipient endpoint, message, message type, check sum/digit)
            string message = "";
            int strlen = 21;
            int msglen = 100;
            string msgtype = "0";// 0 = message, 1 = command
            lclep = Convert.ToString(lclep);
            Debug.Log (lclep);

            while (strlen > lclep.Length)
            {
                Debug.Log('1');
                lclep = lclep + "#";
            }

            string rmtep = "000.00.00.000:8000";

            while (strlen > rmtep.Length)
            {
                Debug.Log ('2');
                rmtep = rmtep + "#";
            }

            while (msglen > x.Length)
            {
                Debug.Log ('3');
                x = x + "#";
            }           

            message = message + lclep + ':' + rmtep + ':' + x + ':' + msgtype + ':';
            Debug.Log(message);

            ASCIIEncoding asen= new ASCIIEncoding();
            byte[] ba = new byte[155];
            ba=asen.GetBytes(message);

            stm.Write(ba,0,ba.Length);

            tcpclnt1.Close();
        }
        catch (Exception e) {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }
}

输出是这样的:

192.168.1.250
The local End point is  :192.168.1.250:8080
Connection accepted from 192.168.1.250:54024
connecting to 192.168.1.250:8080

The local End point is  :192.168.1.250:8000
192.168.1.250
The local End point is  :192.168.1.250:8080

Connection accepted from 192.168.1.250:54055
connecting to 192.168.1.250:8000
192.168.1.250:54055##:000.00.00.000:8000###:message test 1 for stackoverflow####################################################################:0:
147
192.168.1.250:54055##
000.00.00.000:8000###
message test 1 for stackoverflow####################################################################
0
000

如您所见,我没有收到任何错误,所以我所需要的只是一种从多个客户端接收消息的方法。

最佳答案

如果有一个最小的、完整的和可验证的例子会很棒 https://stackoverflow.com/help/mcve但我会针对我理解的问题给出一个可能的解决方案:如何监听多个套接字并同时处理它们的消息。

您可以为每个需要的套接字启动一个线程,这个读取器线程将读取整个消息并发送到另一个线程中的线程安全列表,我将其称为处理线程。最后一个线程会将您的业务逻辑应用于套接字读取的数据,生成响应并将其发送到另一个线程:编写器线程。

Socker -> Readers -> Processor -> Writer

不要像在 Thread3 和 Thread2 方法中那样启动您的线程,这需要过多的 CPU,并且会减慢您的应用程序。预先创建线程,然后以适当的顺序启动。

关于c# - 从所有套接字接收消息而不循环遍历所有套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436346/

相关文章:

c# - 将大型 vb6 应用程序移至 Web 或 winform。你决定!

tcp 消息结束最佳实践

TCP四次握手

c# - 通过 TCP/IP 连接发送时音频不好

c# - 发送二进制文件 TcpClient - 文件大于源

c# - 使用 Autofac 将 log4net 注入(inject) Controller

c# - 使用任务并行库时线程数增长

c# - 像在 C# linq 中一样在 Java 8 中获取匿名对象

c++ - 如何接受 boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 作为 boost::asio::ip::tcp::socket 类型的参数

java - 一台服务器支持多个客户端 Java