473,671 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

got totally confused about the netstream

i am writing a very simple c/s socket program, i just wanted the client to
first write to the server, after server get the message it, write to the
client, the the client write again. here's the codes:

Server:
---------------------------------------------
NetworkStream ns = this.client.Get Stream();
StreamReader reader = new StreamReader(ns );
StreamWriter sw = new StreamWriter(ns );

string kidinfo = reader.ReadLine ();
sw.Write("a");
sw.Flush();
ns.Flush();
sw.Close();

reader.ReadLine ();
---------------------------------------
Client:
--------------------------------------
NetworkStream ns = this.client.Get Stream();
StreamReader sr = new StreamReader(ns );
StreamWriter sw = new StreamWriter(ns );
sw.Write(this.i nterval.ToStrin g());
sw.Flush();
sw.Close();
ns.Flush();

string ps = sr.ReadLine();

sw.Write("ok");
sw.Flush();
sw.Close();
--------------------------------------------------

running them, exceptions came out at the secong "sr.ReadLin e()" of the
server and the first "sr.ReadLin e()" of the client telling me that "Cannot
access a disposed object.", if i renew the StreamReader as "sr = new
StreamReader(ns )", exception came out telling me "stream is not readable".

it seems that the StreamReader can not work well after the StreamWriter
wrote something.

who can tell me why and how to do this?
thx in advanced
Oct 25 '06 #1
7 3040
Hi,

The basic issue with your code is that you are creating StreamReader and
StreamWriter objects on the same NetworkStream object. So when you close
StreamWriter object or StreamReader object it closes the underlying
NetworkStream object thus making it useless for any further reading or
writing.

So correct this in your code.

Hope this helps.

--
Regards,
Aditya.P
"fairyvoice " wrote:
i am writing a very simple c/s socket program, i just wanted the client to
first write to the server, after server get the message it, write to the
client, the the client write again. here's the codes:

Server:
---------------------------------------------
NetworkStream ns = this.client.Get Stream();
StreamReader reader = new StreamReader(ns );
StreamWriter sw = new StreamWriter(ns );

string kidinfo = reader.ReadLine ();
sw.Write("a");
sw.Flush();
ns.Flush();
sw.Close();

reader.ReadLine ();
---------------------------------------
Client:
--------------------------------------
NetworkStream ns = this.client.Get Stream();
StreamReader sr = new StreamReader(ns );
StreamWriter sw = new StreamWriter(ns );
sw.Write(this.i nterval.ToStrin g());
sw.Flush();
sw.Close();
ns.Flush();

string ps = sr.ReadLine();

sw.Write("ok");
sw.Flush();
sw.Close();
--------------------------------------------------

running them, exceptions came out at the secong "sr.ReadLin e()" of the
server and the first "sr.ReadLin e()" of the client telling me that "Cannot
access a disposed object.", if i renew the StreamReader as "sr = new
StreamReader(ns )", exception came out telling me "stream is not readable".

it seems that the StreamReader can not work well after the StreamWriter
wrote something.

who can tell me why and how to do this?
thx in advanced
Oct 25 '06 #2
thank you Pasumarthi, but i am still not clear. you say i need two different
NetworkStream to create the StreamReader and StreamWriter respectively, but i
the program there is only one TcpClient, so i can only get one NetworkStream
from the TcpClient.
Is there any way when the server and client need to communicate using both
"StreamRead er" and "StreamWrit er"? how do people usually deal with it in net
programming?
Oct 25 '06 #3
I think what he means is that you really shouldn't close it in your code
like this..

sw.Close();

fairyvoice wrote:
thank you Pasumarthi, but i am still not clear. you say i need two different
NetworkStream to create the StreamReader and StreamWriter respectively, but i
the program there is only one TcpClient, so i can only get one NetworkStream
from the TcpClient.
Is there any way when the server and client need to communicate using both
"StreamRead er" and "StreamWrit er"? how do people usually deal with it in net
programming?
Oct 25 '06 #4
Hi fairyvoice,

Jianwei is right. I did not mean that you should create two NetworkStreams
out of your TcpClient. What I meant was that you _should not_ close the
StreamReader or StreamWriter attached to the underlying NetworkStream object.

ALso you need not always create StreamReader and StreamWriter objects to
read/write to a NetworkStream. NetworkStream class itself offer you methods
like Write and Read to send and receive data. Check these methods. Using
these methods you can avoid using StreamReader and StreamWriter classes.

Hope this helps.

--
Regards,
Aditya.P
"Jianwei Sun" wrote:
I think what he means is that you really shouldn't close it in your code
like this..

sw.Close();

fairyvoice wrote:
thank you Pasumarthi, but i am still not clear. you say i need two different
NetworkStream to create the StreamReader and StreamWriter respectively, but i
the program there is only one TcpClient, so i can only get one NetworkStream
from the TcpClient.
Is there any way when the server and client need to communicate using both
"StreamRead er" and "StreamWrit er"? how do people usually deal with it in net
programming?
Oct 26 '06 #5
Adityanand Pasumarthi <Ad************ ******@discussi ons.microsoft.c om>
wrote:
Hi fairyvoice,

Jianwei is right. I did not mean that you should create two NetworkStreams
out of your TcpClient. What I meant was that you _should not_ close the
StreamReader or StreamWriter attached to the underlying NetworkStream object.

ALso you need not always create StreamReader and StreamWriter objects to
read/write to a NetworkStream. NetworkStream class itself offer you methods
like Write and Read to send and receive data. Check these methods. Using
these methods you can avoid using StreamReader and StreamWriter classes.
Well, you can avoid them if you only want to write binary data or if
you want to manually do the transformation between text and binary
data. If you're only writing/reading text, using
StreamReader/StreamWriter is a good way to go.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 26 '06 #6
thanks Adityanand and Jianwei. I tried the read and write mathord of the
NetworkStream class and it worked, but i am still a little bored of the
translation between string and bytes. any way, there seems not some perfect
thing in the world
Oct 26 '06 #7
Hi fairyvoice,

Check this self contained class below. It may be of some use to you in your
net programming.

struct Message
{
public short sequenceNumeber ;
public short length;
public short checksum;
public string data;

public int GetMessageLengt h()
{
return 2 + 2 + 2 + data.Length;
}

public byte[] ToBytes()
{
byte[] msgBytes = new byte[this.GetMessage Length()];
MemoryStream ms = new MemoryStream(ms gBytes);
BinaryWriter bw = new BinaryWriter(ms );
bw.Write(sequen ceNumeber);
bw.Write((short )data.Length);
bw.Write(checks um);
bw.Write(Encodi ng.ASCII.GetByt es(data));
bw.Close();
return msgBytes;
}

public static Message FromBytes(byte[] msgBytes)
{
Message msg = new Message();
MemoryStream ms = new MemoryStream(ms gBytes);
BinaryReader br = new BinaryReader(ms );
msg.sequenceNum eber = br.ReadInt16();
msg.length = br.ReadInt16();
msg.checksum = br.ReadInt16();
msg.data = Encoding.ASCII. GetString(br.Re adBytes(msg.len gth));
br.Close();
return msg;
}
}

The above structure can be used like this...

Message msg = new Message();
msg.sequenceNum eber = 1;
msg.data = "Aditya";
msg.checksum = 90;
msg.length = (short) msg.data.Length ;
byte[] msgBytes = msg.ToBytes();
Message msgTemp = Message.FromByt es(msgBytes);
Console.WriteLi ne(msg.data);

The exact structure may not be useful to you but the approach will give you
some ideas on encapsulating complex data structure to byte conversions for
passing messages between client and server apps.

Hope this helps.

--
Regards,
Aditya.P
"fairyvoice " wrote:
thanks Adityanand and Jianwei. I tried the read and write mathord of the
NetworkStream class and it worked, but i am still a little bored of the
translation between string and bytes. any way, there seems not some perfect
thing in the world
Oct 26 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

54
6546
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature here, that feature there. Variations on style are of no interest to me. I'm coming at this from a...
11
2281
by: James Gregory | last post by:
I'm pretty sure this is non-totally-trivial enough and standard-C++ enough to post here, however much it may initially look like a "how do I make a computer game?" question, though I may be wrong. I'm loading a bitmap, and as I'm using Linux I've had to define BITMAPFILEHEADER myself (maybe better practice would be to give my version a new name or whatever, I dunno). Windows uses WORDs and DWORDs to define it, I've used some...
10
3034
by: Lauren Wilson | last post by:
Ok I have searched the MS website for info on this. I am totally confused. If I want to deploy an Access 2003 app and allow my users to run it using Access 2003 Runtime, where do I get the Runtime? I just purchased Office 2003 Professional. Is Access 2003 Runtime included with that or not? It APPEARS that the only way I can get Access 2003 Runtime is to
0
1723
by: Help | last post by:
What are the parameters in the constructor if you are going to send a file over a tcp/ip network using netstream and filestream? I have learned that you are supposed to do something like this: NetStream nstream = new netStream(client); FileStream fstream = new File ("c:\\test.txt", FileMode.open);
13
2300
by: Larry Woods | last post by:
I am creating a "from-to" set of listboxes where the "left" listbox had a list of values and I want to be able to select these values, 1 at a time, and move them into a "right" listbox, removing the selected value from the left listbox. When you select any member from the left listbox and click on the button to move it to the right listbox, everything works fine. If you select the LAST member in the left listbox, and click on the button...
7
2042
by: chad | last post by:
let's say I'm transferring a large file like 100MB over to a folder. The program detects when the file arrives. However, I can't figure out how to know when the file is totally transferred over. One unsuccessful method is to... dim fi as new fileinfo(newfile) fi.length returns the supposed size of the file. But it correctly
6
998
by: Sam Malone | last post by:
Am I just totally missing something here? I'm just new to VS.NET 2005 (using VB.NET) and ADO.NET. I get the impression that ADO.NET can't do what I'm used to doing with ADO (previous ADO withVB6). I used to bind (let's say a text box) to a field (column) in a recordset and if I typed a value in that textbox and tabbed out of it, the value in the database got updated without me having to do anything else. Now what I see is a terribly...
6
2008
by: stef mientki | last post by:
hello, I've thought many times I finally understood the import / namespace rules, but again I'm totally lost :-( This is my library file # Module lib_test.py X = 1
1
7814
by: Stwange | last post by:
I'm currently loading flv videos in swf using the NetStream, NetConnect(null) and Video objects, but how do I set the video to autorepeat? I can't find a method for it in any of the APIs for the above, and I don't really want to write code to wait the length of the video before replaying. Any suggestions will be greatly appreciated, thank-you.
0
3876
by: eliana | last post by:
Hi i'm writing a simple player to stream a flv file; video streams fine but the netstream onstatus and the nestream onmetadata are not invoked. Any help? Here is my code: var nc:NetConnection = new NetConnection; var ns:NetStream; var bufferLength:Number = 3; var fileToPlay:String; initCon();
0
8478
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8397
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8599
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4225
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2813
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2052
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.