C# Client/Server: using Streamreader/writer

前端 未结 4 1080
野性不改
野性不改 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().

提交回复
热议问题