C#异步套接字消息可以等待另一个5秒的下一个套接字消息?

时间:2011-03-29 03:29:23

标签: c# visual-studio c#-4.0 c#-3.0 c#-2.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秒内没有收到任何东西,我将继续处理第一个。请指教。谢谢。

1 个答案:

答案 0 :(得分:1)

为什么不让消息处理线程一直运行?您向其发布消息并让它处理其他处理逻辑,例如等待另外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<T>)。您还可以在消息处理线程上使用BeginInvoke来处理异步处理。