473,791 Members | 3,071 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Existance of networkstream

Hi
I have a simple question. Here is the code related to my question:

while (true)
{
if (tcpListenerSer ver.Pending() && !this.Disposing )
{
TcpClient tcpClient =
tcpListenerServ er.AcceptTcpCli ent();

downloadThreadC lass obj = new
downloadThreadC lass(tcpClient. GetStream());

Thread myThread = new Thread(new
ThreadStart(obj .downloadThread Function));
myThread.Start( );

}
}

TcpClient object returned by AccepTcpClient is destroyed right after program
leaved 'if' block.
before program do this, i'am passing NetworkStream from tcpClient to the
thread which is proceeding some task on this stream.
The question is will it work? The stream is retreved but tcpClient will not
exist during operations on this stream.
Thanks
PK
Jun 19 '06 #1
2 4101
"PiotrKolodziej " <pi************ *@gmail.com> wrote:
I have a simple question. Here is the code related to my question:

while (true)
{
if (tcpListenerSer ver.Pending() && !this.Disposing )
{
This forms a busy polling loop, which will waste CPU resources and will
starve other processes and threads. It's better to call a method which
will block (possibly with a timeout). After every timeout, you can then
check if the listening thread should be shut down. For example, check
out Socket.Poll() with SelectMode.Sele ctRead. You can get the listening
socket behind the TcpListener from its Server property.

Alternatively, you can cancel the blocking call to AcceptTcpClient by
calling Stop() on the server on a different thread. For example:

---8<---
using System;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;

class App
{
static void Main()
{
TcpListener server = new TcpListener(200 0);
ManualResetEven t serverRunning = new ManualResetEven t(false);

Thread serverThread = new Thread(delegate ()
{
server.Start();
serverRunning.S et();
try
{
for (;;)
{
TcpClient client = server.AcceptTc pClient();
}
}
catch (SocketExceptio n ex)
{
// Blocking interrupted
}
});
serverThread.St art();
// prevent race to server.Stop() before server.Start()
serverRunning.W aitOne();

Console.Write(" Press Enter to stop listening...");
Console.ReadLin e();
server.Stop();
serverThread.Jo in();
}
}
--->8---
TcpClient tcpClient =
tcpListenerServ er.AcceptTcpCli ent();

downloadThreadC lass obj = new
downloadThreadC lass(tcpClient. GetStream());

Thread myThread = new Thread(new
ThreadStart(obj .downloadThread Function));
myThread.Start( );

}
}

TcpClient object returned by AccepTcpClient is destroyed right after program
leaved 'if' block.
The variable called 'tcpClient' goes out of scope, but the object it
references (on the managed heap) is not disposed of.
before program do this, i'am passing NetworkStream from tcpClient to the
thread which is proceeding some task on this stream.
The question is will it work? The stream is retreved but tcpClient will not
exist during operations on this stream.


The NetworkStream object (from TcpClient.GetSt ream()) keeps a reference
to the backing socket (i.e. TcpClient.Clien t), so it keeps it alive from
GC and finalization.

That said, you should dispose of the underlying socket or TcpClient or
an owning NetworkStream when it's done with it (closing/disposing either
of TcpClient or a NetworkStream constructed to own the stream will also
dispose of the socket; TcpClient.GetSt ream() creates an owning
NetworkStream).

The documentation for TcpClient.Close () says that it does not close the
underlying connection, but it is wrong: .NET Reflector shows that it
does in fact close the connection.

-- Barry

--
http://barrkel.blogspot.com/
Jun 19 '06 #2
Hi,

Your question is very easily answered, just pass the TcpClient to the new
downloadThreadC lass instance (instead of its NetworkStream ) .

--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"PiotrKolodziej " <pi************ *@gmail.com> wrote in message
news:99******** *************** ***@news.chello .pl...
Hi
I have a simple question. Here is the code related to my question:

while (true)
{
if (tcpListenerSer ver.Pending() && !this.Disposing )
{
TcpClient tcpClient =
tcpListenerServ er.AcceptTcpCli ent();

downloadThreadC lass obj = new
downloadThreadC lass(tcpClient. GetStream());

Thread myThread = new Thread(new
ThreadStart(obj .downloadThread Function));
myThread.Start( );

}
}

TcpClient object returned by AccepTcpClient is destroyed right after
program leaved 'if' block.
before program do this, i'am passing NetworkStream from tcpClient to the
thread which is proceeding some task on this stream.
The question is will it work? The stream is retreved but tcpClient will
not exist during operations on this stream.
Thanks
PK

Jun 19 '06 #3

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

Similar topics

1
556
by: cmjman | last post by:
I have an issue where networkStream.Write doesn't perform its write downstream from my client program until the network stream is closed. I then see the data that was sent appear on the other side. I am sending a small amound of data and read where data wasn't sent until the buffer reached a larger size. However, there is a TcpClient property call NoDelay that is suppose to eliminate this delay. Here is a snippet of my code below. Can...
1
1819
by: Daniel | last post by:
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;
4
7208
by: 0to60 | last post by:
I have a class that wraps a TcpClient object and manages all the async reading of the socket. It works really nice, and I use it all over the place. But there's this ONE INSTANCE where I create one of these things and it WON'T read data. If I set a breakpoint in my EndRead callback, it never goes off. NOTHING is different from anywhere else I use this class, its just this one place. Now, if I create a second constructor for my class...
1
2651
by: kmacintyre | last post by:
I am trying to us a simple NetworkStream to transfer a file over tcp. This works most of the time, but one specific file never downloads(.mdb file). It seems to close the socket and I get an "unable to write data to transport connection" error. I have tried multiple ways to transfer this file(including remoting, sockets without network stream) and downloaded different examples of client/server byte transfer, all with the same result....
6
3328
by: Ryan | last post by:
Hi, I am confused with how NetworkStream works. My application needs to handle heavy requests sent through TCP socket connection. I use NetworkStream.Read method to get the stream data. The
4
1596
by: Kai Thorsrud | last post by:
Hi! How do i check: if "NetworkStream.Null = true then" it says .Null does not supports type Boolean Thanks /Kai
1
3359
by: hamid_2020 | last post by:
I wrote a class to connect to a server using tcpclient. I need to connect to the server and the connection must be open.Then i need to send request to the server again and again.But the problem is that i can communicate with the servet just for one time,the first time i connect to the server,send data and receive response,but when i want to receive data for another time,there won't be any response.some body help me please,whats the problem???...
0
1346
by: Al Wilkerson | last post by:
Hey, Has anyone ever got a "Unable to read data from transport connected" message after reading data from a streamreader composed of a networkstream. For example: Server TcpListener tcpServer = new TcpListener(localAddr,port);
7
4277
by: littleIO | last post by:
Hi, I'm stuck on a very simple problem and just cant seem to get around it, little help would be much appreciated. I have a server which listens, receives calls, processes them and sends back the results to clients. The code below makes the client application not to respond. Client can send data but is stuck in the process of waiting information back from the server. Any ideas?
0
9669
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
9515
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
10155
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
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
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...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
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();...
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
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.