代码之家  ›  专栏  ›  技术社区  ›  Joe Almore

tcpclient不刷新写入

  •  0
  • Joe Almore  · 技术社区  · 6 年前

    我有这个代码要发送 String 发送到服务器的消息。这些信息应该单独发送,但是 Stream TcpClient 正在将消息发送到 溪流 已关闭。

    如何使用此代码发送分离的消息:

    public void sendData()
    {
        const int PORT_NO = 12900;
        const string SERVER_IP = "127.0.0.1";
    
        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
        try
        {
            client.NoDelay = true;
            NetworkStream nwStream = client.GetStream();
            sendText(nwStream, "Text-1"); // Here is it supposed to send "Text-1"
            sendText(nwStream, "Text-2");
            sendText(nwStream, "Text-3");
        }
        finally
        {
            client.Close(); // But, all messages are sent here!
        }
    }
    
    private void sendText(NetworkStream nwStream, String text)
    {
        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(text);
        nwStream.Write(bytesToSend, 0, bytesToSend.Length);
        nwStream.Flush();            
    }
    

    使用此代码,服务器将接收到: Text-1Text-2Text-3 在一条信息中,它应该会收到3条不同的信息。这里怎么了?

    0 回复  |  直到 6 年前