473,769 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C#.NET - Detecting socket is closed

2 New Member
I'm writing a program that in its most simplest form acts as a proxy between a local client and a remote server. But I cannot figure out how to detect when either the connection to the client is close or the connection to the server is closed. I've tried looking at socket.connecte d - it always returns true, even when the client program has disconnected. I've tried getting an exception from the networkstream.D ataAvailable, it always just reads false, and no exceptions. Anyone know how I can detect when these sockets are remotely closed??

Expand|Select|Wrap|Line Numbers
  1. TcpListener listener;
  2.             TcpClient client;
  3.             TcpClient server;
  4.             while (true)
  5.             {
  6.                 Thread.Sleep(10);
  7.                 IPAddress addy = IPAddress.Parse("127.0.0.1");
  8.                 listener = new TcpListener(addy, 4001);
  9.                 listener.Start();
  10.                 client = listener.AcceptTcpClient();
  11.                 Console.WriteLine("[[Client connected.]]");
  12.                 server = new TcpClient();
  13.                 server.Connect("imperian.com", 23);
  14.                 Console.WriteLine("[[Server connected.]]");
  15.                 NetworkStream cstm = client.GetStream();
  16.                 NetworkStream sstm = server.GetStream();
  17.                 bool quit = false;
  18.                 while (!quit)
  19.                 {
  20.                     Thread.Sleep(10);
  21.  
  22.                     if (!client.Client.Connected)
  23.                     {
  24.                         Console.WriteLine("[[Client disconnected]]");
  25.                     }
  26.  
  27.                     try
  28.                     {
  29.                         if (cstm.DataAvailable)
  30.                         {
  31.                             byte[] readBuffer = new byte[1024];
  32.                             StringBuilder builder = new StringBuilder();
  33.                             int numBytes = 0;
  34.                             do
  35.                             {
  36.                                 numBytes = cstm.Read(readBuffer, 0, readBuffer.Length);
  37.                                 builder.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer));
  38.                             } while (cstm.DataAvailable);
  39.  
  40.                             byte[] writeBuffer = Encoding.ASCII.GetBytes(builder.ToString());
  41.                             sstm.Write(writeBuffer, 0, writeBuffer.Length);
  42.                         }
  43.  
  44.                         if (sstm.DataAvailable)
  45.                         {
  46.                             byte[] readBuffer = new byte[1024];
  47.                             StringBuilder builder = new StringBuilder();
  48.                             int numBytes = 0;
  49.                             do
  50.                             {
  51.                                 numBytes = sstm.Read(readBuffer, 0, readBuffer.Length);
  52.                                 builder.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer));
  53.                             } while (sstm.DataAvailable);
  54.  
  55.                             byte[] writeBuffer = Encoding.ASCII.GetBytes(builder.ToString());
  56.                             cstm.Write(writeBuffer, 0, writeBuffer.Length);
  57.                         }
  58.                     }
  59.                     catch (Exception)
  60.                     {
  61.                         cstm.Close();
  62.                         Console.WriteLine("[[Client disconnected.]]");
  63.                         sstm.Close();
  64.                         Console.WriteLine("[[Server disconnected.]]");
  65.                         break;
  66.                         quit = true;
  67.                     }
  68.                 }
  69.             }
Aug 8 '08 #1
5 42107
joedeene
583 Contributor
here is a link to a great response similar to your problem.

http://bytes.com/forum/thread234523.html

at the bottom of the linked page, it says something about the .poll() function of the socket class, i think that will help
Aug 8 '08 #2
Plater
7,872 Recognized Expert Expert
I wrote this code and use it frequently:
Expand|Select|Wrap|Line Numbers
  1. bool SocketConnected(Socket s)
  2. {
  3.    bool part1 = s.Poll(1000, SelectMode.SelectRead);
  4.    bool part2 = (s.Available == 0);
  5.    if (part1 & part2)
  6.    {//connection is closed
  7.       return false;
  8.    }
  9.    return true;
  10. }
  11.  
Aug 8 '08 #3
tichi
2 New Member
Thank you so much, that worked!
Aug 8 '08 #4
ddboarm
1 New Member
I used that code and it works wonderfully...t hanks a bunch!!!
Nov 9 '09 #5
anhhuycan83
1 New Member
to: Plater Plater
You are very good. After searching on google in many hours, but I can not find any working solutions. Now, I used that code and it works wonderfully...t hanks a bunch!!!
good job!
Jul 8 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
7622
by: Tim Gosselin | last post by:
I am writing a tcp tunnel but cannot find a way of detecting when a socket shuts down its read end without writing to the socket. For testing the write end of the remote endpoint I just do a: if not sock.recv(buffsize) I cannot write to the socket and check if send returns 0 though, because that involves sending data out of the which may not have come in yet. When I try polling the socket with:
6
18506
by: Michael Kennedy [UB] | last post by:
Hi, I have a project using the TcpClient and its associated NetworkStream. Everything works well except for one condition which I haven't found any information about dealing with: How do I detected when the socket connection was closed on the server-side? That is, if my client connects to the server and everything is initialized
0
1194
by: Jonathan | last post by:
Hi, how to detect when an asynchronous socket is closed? Thanks!
1
700
by: rs | last post by:
how I the client tell the server that the socket is closed? or this there an even that informs the server that the clients socket is close? Oh, I am using vb.net 2003 Thanks
4
5227
by: schwehr | last post by:
Hi All, I've tried to RTFM this and am having no luck. First off, I am using Mac OSX 10.4.7 with python 2.4.2 from fink. I am trying to connect to a server that should be rejecting connections and I was surprised when it did not throw an exception or do something otherwise equally nasty. It just connects and never returns any data. First, the proof that something is there and rejecting the connection (or is it that this thing...
5
3108
by: Kurt | last post by:
I have a client & server app which communicates using the socket class. If I shutdown the server closing the socket the client still thinks the socket is open. Even calling send does not throw an exception. Thanks Kurt
2
6538
by: O.B. | last post by:
In the following code snippet, the thread successfully makes it to the line where it waits for data to be received. Then the client closes the connection. The thread wakes up and returns from the WaitOne() operation. No exception is thrown when it loops and executes BeginReceive() again. The WaitOne() operation returns immediately. Thus, there's an endless loop. How does one detect that the remote client has closed the connection in...
11
18047
Plater
by: Plater | last post by:
I'm having a bit of trouble figuring out how to detect if a socket is closed or not. Outside of using read()/write(). I also don't want to set the socket to non-blocking if at all possible. I wrote a function that reads a single char(or byte, whatever) and wanted to use it in a simulated blocking and nonblocking way. It works fine for waiting for the correct timeouts, but since I use ioctl() to detect if there is data to be read, I won't...
0
9423
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,...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
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...
1
9995
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
9863
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
6674
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3962
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
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.