C#使用StreamReader从NetworkStream读取

时间:2012-02-17 09:29:53

标签: c# tcpclient streamreader streamwriter networkstream

我是一名Java开发人员正在尝试构建一个简单的C#TCP客户端。然而,对于我的生活,我无法弄清楚如何使这个血腥的东西工作。这是我的TCPClient代码。顺便说一下,我直接从msdn偷了这个。 http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

    public static void Connect(String server, int port, String message)
    {
        try
        {
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer 
            // connected to the same address as specified by the server, port
            // combination.
            TcpClient client = new TcpClient(server, port);

            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent: {0}", message);

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = Encoding.ASCII.GetString(data, 0, bytes);
            Console.WriteLine("Received: {0}", responseData);

            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

这是我的Java服务器。

private ServerSocket socket;
private JAXBContext jaxbContext;
boolean listening = true;

@SuppressWarnings("unused")
private HMSAgentService() {

}

public HMSAgentService(int port) {
    try {
        this.socket = new ServerSocket(port);
        logger.debug("Agent Service listening on port : " + port);
        this.jaxbContext = HMSAgentUtil.getJAXBContext();
        while (listening) {
            new AgentServiceThread(socket.accept(), jaxbContext).start();
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } catch (JAXBException e) {
        logger.error(e.getMessage(), e);
    }

}

它只是在收到客户端连接时启动一个新线程。 现在我的问题是程序永远不会移过stream.Write()。服务器也永远不会收到消息。只有在我调用Stream.close()之后,服务器才会收到消息。但这基本上会关闭连接,客户端无法再接收任何消息。为什么会这样。我尝试过使用Sockets,StreamWriters,StreamReaders和它的故事。 此时我正在考虑使用异步方法,但我试图让程序尽可能简单,因为不需要它。无论如何都会发出写信结束的信号?

0 个答案:

没有答案