C# Client/Server: using Streamreader/writer

前端 未结 4 1081
野性不改
野性不改 2020-12-10 21:43

I\'m relatively new to C# but here goes:

I am developing a remote file service client/server console application in C# which is supposed to exchange messages using

相关标签:
4条回答
  • 2020-12-10 21:52

    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().

    0 讨论(0)
  • 2020-12-10 21:59

    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/

    0 讨论(0)
  • 2020-12-10 22:02

    Solution can be simpler:

    StreamWriter wr = new StreamWriter(stream) { AutoFlush = true }
    
    0 讨论(0)
  • 2020-12-10 22:10

    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();
    
    0 讨论(0)
提交回复
热议问题