473,383 Members | 1,984 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,383 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 41489
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.