473,406 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

C#.NET - Detecting socket is closed

2
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.connected - it always returns true, even when the client program has disconnected. I've tried getting an exception from the networkstream.DataAvailable, 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

✓ answered by Plater

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.  

5 41516
joedeene
583 512MB
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 Expert 4TB
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
Thank you so much, that worked!
Aug 8 '08 #4
I used that code and it works wonderfully...thanks a bunch!!!
Nov 9 '09 #5
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...thanks a bunch!!!
good job!
Jul 8 '10 #6

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

Similar topics

1
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...
6
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...
0
by: Jonathan | last post by:
Hi, how to detect when an asynchronous socket is closed? Thanks!
1
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
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...
5
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...
2
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...
11
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...

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.