C# Client/Server: using Streamreader/writer

拟墨画扇 提交于 2019-12-01 10:38:14

I think you're just missing a wr.flush(); but this article should cover everything you need:

http://thuruinhttp.wordpress.com/2012/01/07/simple-clientserver-in-c/

Xyed Xain Haider

Whenever you use StreamWriter you need to Flush() the contents of the stream. I'll quote MSDN as the reason becomes quite clear:

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

You can call it quite simply like:

wr.flush();

I just ran a test using your code, and it works fine, I can step right into the "one" case statement.

I am guessing you are either not including the line-break in the string you are sending, or you just have the TcpClient or TcpListener configured wrong.

Here is the Client-Side code for my test:

        TcpClient client = new TcpClient("127.0.0.1", 13579);
        string message = "one" + Environment.NewLine;
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
        NetworkStream stream = client.GetStream();
        stream.Write(data, 0, data.Length);

Here is the Server-Side:

        IPAddress localAddr = IPAddress.Parse("127.0.0.1");
        TcpListener server = new TcpListener(localAddr, 13579);
        server.Start();

        TcpClient client = server.AcceptTcpClient();
        using (client)
        using (NetworkStream stream = client.GetStream())
        using (StreamReader rd = new StreamReader(stream))
        using (StreamWriter wr = new StreamWriter(stream))
        {
            string menuOption = rd.ReadLine();
            switch (menuOption)
            {
                case "1":
                case "one":
                    string passToClient = "Test Message!";
                    wr.WriteLine(passToClient);
                    break;
            }
            while (menuOption != "4") ;
        }

Just run the server-side code first, which will block while waiting for connection and then while waiting for data. Then run the client-side code. You should be able to catch a breakpoint on the switch().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!