将消息写入套接字而无需建立永久连接

时间:2018-06-20 15:50:30

标签: c# sockets networking

我想从消息队列中读取消息,而每次建立一个完整的新连接时都不会建立消息,因为在我有很多消息的情况下,建立连接会花费太多时间。 我考虑过要使客户端的Networkstream保持打开状态的办法,但是后来我遇到了一个问题,我不知道我可以写多少和多长时间。 有什么建议可以使我更快地将消息写入客户端,而不必每次都建立新的连接?谢谢!

  XmlMessageFormatter msgFormatter = new XmlMessageFormatter(new String[] { "System.String, mscorlib" });
        TcpClient tcpClient = new TcpClient();
        NetworkStream clientSockStream = tcpClient.GetStream();

        MessageQueue messageQueue = new MessageQueue(@".\Private$\MsgQueue");

        while(true)
        {
            Message peekMessage = messageQueue.Peek();
            SettingsHandler.WriteDebug("Message arrived ! Total: " + messageQueue.GetAllMessages().Length.ToString());

            try
            {
                tcpClient.Connect(SettingsHandler.serverAddress, SettingsHandler.serverPort);
                // read from queue
                Message message = messageQueue.Receive();
                message.Formatter = msgFormatter;
                // send to server
                byte[] sendBytes = Encoding.UTF8.GetBytes(message.Body.ToString());
                clientSockStream.Write(sendBytes, 0, sendBytes.Length);
                clientSockStream.Close();
                tcpClient.Close();
            }
            catch (Exception e)
            {
                SettingsHandler.WriteDebug("SocketException: {0}" + e.Message);
                SettingsHandler.WriteDebug("Server not available, retry in 5 seconds. !");
                Thread.Sleep(5000);

            }
        }

0 个答案:

没有答案