C# 异步套接字消息可以再等待 5 秒以获得下一个套接字消息吗?

发布于 2024-10-28 05:08:21 字数 3030 浏览 1 评论 0原文

在我的项目中,我使用异步套接字服务器,如下所示。

for (int i = 0; i < localip.Length; i++)
                {
                    try
                    {


                        m_mainSocket[1] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        m_mainSocket[1].Bind(new IPEndPoint(localip[i], port));
                        m_mainSocket[1].Listen(1000);
                        m_mainSocket[1].BeginAccept(new AsyncCallback(OnClientConnect2), m_mainSocket[1]);
                        Log.updateErrorlog(localip[i].ToString()+" Port : "+port);
                    }
                    catch
                    { }
                }

public void OnClientConnect2(IAsyncResult ar)
        {

            Socket listener2 = (Socket)ar.AsyncState;
            try
            {

                NewConnection2(listener2.EndAccept(ar));
                listener2.BeginAccept(new AsyncCallback(OnClientConnect2), listener2);
            }
            catch
            {

                listener2.Close();

            }
        }
        public void NewConnection2(Socket sockClient)
        {
            SocketChatClient client2 = new SocketChatClient(sockClient);
            //m_aryClients.Add(client2);
            client2.SetupRecieveCallback2(this);
            if (!InvokeRequired)
            {

            }
            else
            {

            }
        }

        public void WaitForData(System.Net.Sockets.Socket soc)
        {

            SocketChatClient client2 = new SocketChatClient(soc);
            client2.SetupRecieveCallback2(this);

        }

        public void OnDataReceived(IAsyncResult ar)
        {

            SocketChatClient client = (SocketChatClient)ar.AsyncState;
            byte[] aryRet = client.GetRecievedData(ar);
            string mdz3 = "";
            mdz3 = System.Text.Encoding.ASCII.GetString(aryRet, 0, aryRet.Length);

            if (aryRet.Length < 1)
            {
                client.Sock.Close();

                return;
            }

            messageReceived msend = new messageReceived(mdz3, aryRet, client.Sock);
            msend.msg_thread.Start();

            msend.msg_thread.Join();

            client.SetupRecieveCallback2(this);


        }

并且,下面是我的 messageReceived .cs 类。

public Thread s_thread;
        private string RecvData;
        private Random RNo = new Random();
        private Socket ClientSocket;

        public MsgThread(byte[] aryRecvData,Socket _ClientSocket)
        {
            RecvData = System.Text.Encoding.ASCII.GetString(aryRecvData,0,aryRecvData.Length);
            ClientSocket = _ClientSocket;
            s_thread = new Thread(new ThreadStart(ProcessThread));
        }

private void MsgThreadProcess()
        {
            lock (this)
            {
string[] msg = RecvData.Split('|');
Process(msg);
            }
        }

当我收到第一个套接字消息时,我想再等待 5 秒以获取第二个套接字消息并处理两条消息。如果我在 5 秒内没有收到任何信息,我将继续处理第一个。请指教。谢谢。

In my project , I am using Asynchronous Socket Server As below.

for (int i = 0; i < localip.Length; i++)
                {
                    try
                    {


                        m_mainSocket[1] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        m_mainSocket[1].Bind(new IPEndPoint(localip[i], port));
                        m_mainSocket[1].Listen(1000);
                        m_mainSocket[1].BeginAccept(new AsyncCallback(OnClientConnect2), m_mainSocket[1]);
                        Log.updateErrorlog(localip[i].ToString()+" Port : "+port);
                    }
                    catch
                    { }
                }

public void OnClientConnect2(IAsyncResult ar)
        {

            Socket listener2 = (Socket)ar.AsyncState;
            try
            {

                NewConnection2(listener2.EndAccept(ar));
                listener2.BeginAccept(new AsyncCallback(OnClientConnect2), listener2);
            }
            catch
            {

                listener2.Close();

            }
        }
        public void NewConnection2(Socket sockClient)
        {
            SocketChatClient client2 = new SocketChatClient(sockClient);
            //m_aryClients.Add(client2);
            client2.SetupRecieveCallback2(this);
            if (!InvokeRequired)
            {

            }
            else
            {

            }
        }

        public void WaitForData(System.Net.Sockets.Socket soc)
        {

            SocketChatClient client2 = new SocketChatClient(soc);
            client2.SetupRecieveCallback2(this);

        }

        public void OnDataReceived(IAsyncResult ar)
        {

            SocketChatClient client = (SocketChatClient)ar.AsyncState;
            byte[] aryRet = client.GetRecievedData(ar);
            string mdz3 = "";
            mdz3 = System.Text.Encoding.ASCII.GetString(aryRet, 0, aryRet.Length);

            if (aryRet.Length < 1)
            {
                client.Sock.Close();

                return;
            }

            messageReceived msend = new messageReceived(mdz3, aryRet, client.Sock);
            msend.msg_thread.Start();

            msend.msg_thread.Join();

            client.SetupRecieveCallback2(this);


        }

And , below is my messageReceived .cs class.

public Thread s_thread;
        private string RecvData;
        private Random RNo = new Random();
        private Socket ClientSocket;

        public MsgThread(byte[] aryRecvData,Socket _ClientSocket)
        {
            RecvData = System.Text.Encoding.ASCII.GetString(aryRecvData,0,aryRecvData.Length);
            ClientSocket = _ClientSocket;
            s_thread = new Thread(new ThreadStart(ProcessThread));
        }

private void MsgThreadProcess()
        {
            lock (this)
            {
string[] msg = RecvData.Split('|');
Process(msg);
            }
        }

When I receive the first socket message, I want to wait another 5 seconds for second socket message and process two messages. If I don't receive anything within 5 secs, I will continue processing the first one. Please advise. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明月夜 2024-11-04 05:08:21

为什么不让消息处理线程一直运行呢?您向它发布消息并让它处理其他处理逻辑,例如再等待 5 秒以接收第二条消息。沿着这些思路:

public class MessageProcessor
{
    private Thread _ProcessingThread;
    private Queue<Message> _MessageQueue;
    private AutoResetEvent _MessagePosted;

    public MessageProcessor()
    {
        _MessagePosted = new AutoResetEvent(false);
        _MessageQueue = new Queue<Message>();
        _ProcessingThread = new Thread(ProcessMessages);
        _ProcessingThread.Start();
    }

    public void Post(Message msg)
    {
        _MessageQueue.Enqueue(msg);
        _MessagePosted.Set();
    }

    private void ProcessMessages(object state)
    {
        while (!_Quit)
        {
            _MessagePosted.WaitOne();
            _MessagePosted.WaitOne(TimeSpan.FromSeconds(5));
            ... process message queue
        }
    }
}

在您的消息接收代码中,

messageProcessor.Post(receivedMessage);

您需要添加一些锁定来保护您的队列等(尽管对于.net 4,您有ConcurrentQueue)。您还可以在消息处理线程上使用 BeginInvoke 来处理异步处理。

Why not have your message processing thread running all the time? You post messages to it and let it handle additional processing logic like waiting another 5sec for a second message. Something along those lines:

public class MessageProcessor
{
    private Thread _ProcessingThread;
    private Queue<Message> _MessageQueue;
    private AutoResetEvent _MessagePosted;

    public MessageProcessor()
    {
        _MessagePosted = new AutoResetEvent(false);
        _MessageQueue = new Queue<Message>();
        _ProcessingThread = new Thread(ProcessMessages);
        _ProcessingThread.Start();
    }

    public void Post(Message msg)
    {
        _MessageQueue.Enqueue(msg);
        _MessagePosted.Set();
    }

    private void ProcessMessages(object state)
    {
        while (!_Quit)
        {
            _MessagePosted.WaitOne();
            _MessagePosted.WaitOne(TimeSpan.FromSeconds(5));
            ... process message queue
        }
    }
}

And in your message receiving code you do

messageProcessor.Post(receivedMessage);

You'll need to put in some locking to protect your queue etc. (although for .net 4 you have ConcurrentQueue<T>). You can also use BeginInvoke on your message processing thread to handle the processing async.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文