Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

sockets - C# Client/Server: using Streamreader/writer

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 synchronous sockets.

One of the main problems (even thought it might seem simple) is to return a string from the server, to the client using streamreader/streamwriter.

The application user a command line interface with options (from a switch statement) to execute actions. I.e. typing 1 and enter would execute the code to send the string from the server to the client.

Below is a sample code from the client:

        try
        {
            using (TcpClient client = (TcpClient)clientObject)
            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");
               }
         }

I understand the code I posted is just a snippet of the program, but it would take up a fair amount of space and was hoping you can gather what I mean from this, if not I will post more.

This is just to give a general idea of what I am going for,

I appreciate any help / advice you can give. Its not so much code examples I'm looking for (although a little would help) but more some explanation on streamreader/writer as I cant seem to understand much of what is online.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...