I have a background thread to accept and process TCP/IP connections.
When the application shuts down I want to gracefully terminate it.
The thread will block in NetworkStream.R ead() waiting for data. I
expected that shutting down the TcpListener would unblock the Read()
and cause an exception, or return 0 bytes. But it does not work.
Relevant parts of the code are shown below. If a client connects, the
stream blocks in its Read() method. If Stop() is then called from the
main thread, NetworkStream.R ead() stays blocked even though the
TcpListener has stopped (and thus the underlying socket is closed).
I expect Read() to throw an IOException with an inner SocketException ,
or at least for it to unblock and return 0 bytes. But it doesn't work.
Any suggestions would be appreciated.
private TcpListener _listener;
public void StartListening( )
{
_listener = new TcpListener(end Point);
_listener.Start ();
Thread thread = new Thread(new ThreadStart(thi s.Process));
thread.Start();
}
public void StopListening()
{
_listener.Stop( );
}
private void Process()
{
while (true)
{
try
{
TcpClient client = _listener.Accep tTcpClient();
NetworkStream strm = client.GetStrea m();
while (true)
{
int bytesRead = strm.Read(buf, 0, buf.Length);
// ... process ...
}
}
catch (IOException e)
{
// Expect a SocketException when the listener stops
}
}
} 4 7556
Dave,
I don't understand why you are looping infinitely. Why not use the
BeginAcceptTcpC lient and BeginRead methods to perform your work? You
wouldn't have to block a thread and poll. You would just be notified when
the client is available, and when your read was complete.
It would also use less resources, since you would be using I/O
completion ports (under the wrappers) instead of tying up a thread.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"DaveR" <NOSPAM_drubin@ NOSPAM_i-2000.com> wrote in message
news:Pa******** *************** ***@4ax.com... I have a background thread to accept and process TCP/IP connections. When the application shuts down I want to gracefully terminate it.
The thread will block in NetworkStream.R ead() waiting for data. I expected that shutting down the TcpListener would unblock the Read() and cause an exception, or return 0 bytes. But it does not work.
Relevant parts of the code are shown below. If a client connects, the stream blocks in its Read() method. If Stop() is then called from the main thread, NetworkStream.R ead() stays blocked even though the TcpListener has stopped (and thus the underlying socket is closed).
I expect Read() to throw an IOException with an inner SocketException , or at least for it to unblock and return 0 bytes. But it doesn't work.
Any suggestions would be appreciated.
private TcpListener _listener; public void StartListening( ) { _listener = new TcpListener(end Point); _listener.Start (); Thread thread = new Thread(new ThreadStart(thi s.Process)); thread.Start(); }
public void StopListening() { _listener.Stop( ); }
private void Process() { while (true) { try { TcpClient client = _listener.Accep tTcpClient(); NetworkStream strm = client.GetStrea m(); while (true) { int bytesRead = strm.Read(buf, 0, buf.Length); // ... process ... } } catch (IOException e) { // Expect a SocketException when the listener stops } } }
"DaveR" <NOSPAM_drubin@ NOSPAM_i-2000.com> wrote in message
news:Pa******** *************** ***@4ax.com... I have a background thread to accept and process TCP/IP connections. When the application shuts down I want to gracefully terminate it.
The thread will block in NetworkStream.R ead() waiting for data. I expected that shutting down the TcpListener would unblock the Read() and cause an exception, or return 0 bytes. But it does not work.
.... private void Process() { while (true) { try { TcpClient client = _listener.Accep tTcpClient(); NetworkStream strm = client.GetStrea m(); while (true) { int bytesRead = strm.Read(buf, 0, buf.Length); // ... process ... } } catch (IOException e) { // Expect a SocketException when the listener stops } } }
First, you are blocking accept while processing. When accept returns, you
should start new thread and process accepted connection on that thread. In
current implementation, you will not be able to process more than one
connection at the time.
To stop blocking read on TcpClient, you have to close tcpclient returned
from Accept, not listener. These two are unrelated. For that, you'll
probably have to track accepted connection (and remove them when they
disconnect).
Goran
The listener socket is seperate from the accepted socket (i.e. two different
objects). Stopping the listener, just stops the listener, not all
connected sockets. To shutdown connected sockets, you would need to walk a
list and close each one. hth
--
William Stacey [MVP]
"DaveR" <NOSPAM_drubin@ NOSPAM_i-2000.com> wrote in message
news:Pa******** *************** ***@4ax.com...
|I have a background thread to accept and process TCP/IP connections.
| When the application shuts down I want to gracefully terminate it.
|
| The thread will block in NetworkStream.R ead() waiting for data. I
| expected that shutting down the TcpListener would unblock the Read()
| and cause an exception, or return 0 bytes. But it does not work.
|
| Relevant parts of the code are shown below. If a client connects, the
| stream blocks in its Read() method. If Stop() is then called from the
| main thread, NetworkStream.R ead() stays blocked even though the
| TcpListener has stopped (and thus the underlying socket is closed).
|
| I expect Read() to throw an IOException with an inner SocketException ,
| or at least for it to unblock and return 0 bytes. But it doesn't work.
|
| Any suggestions would be appreciated.
|
| private TcpListener _listener;
| public void StartListening( )
| {
| _listener = new TcpListener(end Point);
| _listener.Start ();
| Thread thread = new Thread(new ThreadStart(thi s.Process));
| thread.Start();
| }
|
| public void StopListening()
| {
| _listener.Stop( );
| }
|
| private void Process()
| {
| while (true)
| {
| try
| {
| TcpClient client = _listener.Accep tTcpClient();
| NetworkStream strm = client.GetStrea m();
| while (true)
| {
| int bytesRead = strm.Read(buf, 0, buf.Length);
| // ... process ...
| }
| }
| catch (IOException e)
| {
| // Expect a SocketException when the listener stops
| }
| }
| }
On Tue, 30 May 2006 16:44:16 -0400, "Nicholas Paldino [.NET/C# MVP]"
<mv*@spam.guard .caspershouse.c om> wrote: I don't understand why you are looping infinitely. Why not use the BeginAcceptTcp Client and BeginRead methods to perform your work?
I have used that before in a server that needed to process many
simultaneous connections, but in this case we need to handle only a
single connection at a time, so I thought the asynchronous operation
may be overkill. Maybe that was not a wise choice.
In any case, I solved the problem by making the TcpClient a member and
closing it from the main thread, which effectively unblocks the
NetworkStream.R ead as I wanted. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Stelrad Doulton |
last post by:
Hi all,
I am writting a Jabber-esque client-server application and have run into an
issue with the XmlTextReader constructor when passing a NetworkStream - It
hangs forever, apparently this is an issue with SP1.
Anyway I have the code below as a work around (using bool keepalives as it
must run on the CF):
while(keepAlive)
|
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...
|
by: psg |
last post by:
Hello!
I am developing Windows application which after sending a request to a
server will listen to response, a response will be infinite in length, but
will not be continuous in time.
What I have done is in a back thread I prepared infinite loop and there I am
checking for new packages. Its scheme looks like this:
***********************************
|
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....
|
by: Abubakar |
last post by:
Hi,
try
{
int x = ns.Read(readbuffer, 0, readbuffer.Length);
}
catch (System.IO.IOException ioexception)
{
UINotifications.ServerMessageDisplay(ioexception.ToString( ));
}
| |
by: Kevin |
last post by:
In a newsgroup thread from Jan 8, 2003 between Barry Holsinger and the
VBDotNet Team, please review this excerpt:
"You understood my problem completely. Your sample code provides a
really
elegant way to inject CrLf into the input stream, which effectively
unblocks
the ReadLine method. Last night, I had finally got the
WriteConsoleInput
|
by: |
last post by:
I've got a basic "chat" infrastructure that can send objects across the wire, but I'm running into a few issues with trying to send multiple messages and things behaving differently in debug and release...
Is there anyone out there that considers themselves a threading / sockets / serialization guru? Not sure if it's appropriate to post an entire project here and the issues discussion is probably a bit too complex for newsgroup back and...
|
by: ohmmega |
last post by:
hello out there,
I use a thread data from a linuxserver. i ask for data, i read the
data (fix in size) - so far so good. this works great for the first 61
datapackages, then my thread abruptly freezes, because of the read
method. i can't locate the real reason. if I reconnect the tcpClient
after each package it works fine, but after several minutes the linux
programm quits (not my fault, not my code, not to change). has anybody
any...
|
by: Ryan Liu |
last post by:
Hi, I have some basic question about NetworkStream, can someone explain to
me? Thanks a lot in advance!
TcpClient has a GetStream() method return a NetworkStream for read and
write.
I remember there are 2 streams in Java, one for read, one for write.
If I just use synchronous Read() and Write() method:
|
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,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
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,...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |