knowing when data sent so i can close the streamwriter and networkstream

D

Daniel

i would like to konw when the data sent so that i can close the streamwriter
and networkstream is there some sort of call backs/events i have to
implement for this to work? if so how? can i just open neworkstream and
streamwriter, send data and then close it syncrhronously or do i have to
implement some callbacks/events to do this like in vb6?



TcpClient myclient;

myclient = new TcpClient("localhost", 1234);

NetworkStream networkStream ;

networkStream = myclient.GetStream();

StreamWriter streamWriter ;

streamWriter = new StreamWriter(networkStream);


streamWriter.WriteLine("<ratpack1324><ratpack1324><ratpack1324><ratpack1324>
<ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack132
4><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1
324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324>v<ratpa
ck1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><rat
pack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><r
atpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324><ratpack1324>
<ratpack1324><ratpack1324><ratpack1324>");

streamWriter.Flush();

streamWriter.Close() ;

networkStream.Close();
 
J

Jon Skeet [C# MVP]

Daniel said:
i would like to konw when the data sent so that i can close the streamwriter
and networkstream is there some sort of call backs/events i have to
implement for this to work? if so how? can i just open neworkstream and
streamwriter, send data and then close it syncrhronously or do i have to
implement some callbacks/events to do this like in vb6?

You should just be able to write with no problems - closing will flush,
basically.

Note that it's worth using a "using" statement to make the code close
the connection even if an exception is thrown. You can also simplify
things a bit by not having a separate variable for the network stream:

using (TcpClient myClient = new TcpClient ("localhost", 1234))
{
using (StreamWriter streamWriter = new StreamWriter
(myClient.GetStream())
{
streamWriter.WriteLine ("...");
}
}

(Admittedly you *could* turn it into one using statement, with

using (StreamWriter writer = new StreamWriter (new TcpClient
("localhost", 1234).GetStream())
{
....
}

but I think that's going a bit far.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top