473,385 Members | 1,427 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,385 software developers and data experts.

determine if Socket is connected

Hi all,
I view many posts about this issue , the connected property does not tell us the current status of the socket.

based on couple of suggestions of msdn , and some article here , I try to write an helper method that will tell if the socket is connected or not , but it's not working good
continue to tell me that the socket is connectedeven if the other party already call shutdown(both) + close , or , even if the other party close the app itslef.
also I determine different behaviour when my app running behind NAT
when I run behind NAT , calling to socket.Receive(..) throw exception which was good forme to determine that it's already closed the connection , it doesn't throw nothing when I run the same code without NAT

Here is my code:

/// <summary>

/// Determine if the givven socket is connected or not

/// </summary>

/// <remarks>

/// There is a problem to based the Socket.Connected property since it's show the last operaion status: (from msdn)

/// The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.

/// The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

/// </remarks>

/// <seealso cref="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/3cf03e0641731659/76e2563d28f1b256?lnk=st&q=c%23+determine+if+socket +connected&rnum=5#76e2563d28f1b256"/>

/// <seealso cref="http://windowssdk.msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx"/>

/// <returns>Bool , True if connected , False if not</returns>

public static bool IsConnected(Socket checkSocket)

{

try

{

//if (checkSocket.GetSocketOption(SocketOptionLevel.Soc ket, SocketOptionName.KeepAlive, 1)[0].Equals(1))

// return checkSocket.Connected;

if (checkSocket.Connected == false)

return false;

//checkSocket.BeginSend(new byte[0], 0, 0, SocketFlags.None, null, null);

bool bSelectRead = checkSocket.Poll(1, SelectMode.SelectRead);

bool bSelectWrite = checkSocket.Poll(1, SelectMode.SelectWrite);

int available = checkSocket.Available;

//if (bSelectWrite && bSelectRead && available 0)

if (bSelectWrite && bSelectRead)

{

//return true;

//checkSocket.BeginReceive(new byte[1], 0, 1, SocketFlags.Peek, null, null);

checkSocket.Receive(new byte[0], 0, 0, SocketFlags.Peek);

checkSocket.Send(new byte[0], 0, 0, SocketFlags.None);

return checkSocket.Connected;

}

else

return false;

}

catch (SocketException)

{

return false;

}

catch (ObjectDisposedException)

{

return false;

}

}

here is MS code , that also don't work - tell that the socket is connected even if the other party already close...

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
byte [] tmp = new byte[1];

client.Blocking = false;
client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
Console.WriteLine("Still Connected, but the Send would block");
else
{
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
client.Blocking = blockingState;
}

Console.WriteLine("Connected: {0}", client.Connected);
Sep 21 '06 #1
7 16884
So... this method is something many developers need , there are noting in
..NET that already do it ?
"Vadym Stetsyak" <va*****@ukr.netwrote in message
news:uo**************@TK2MSFTNGP06.phx.gbl...
Hello, semedao!

sbased on couple of suggestions of msdn , and some article here , I try
sto write an helper method that will tell if the socket is connected or
snot , but it's not working good continue to tell me that the socket is
sconnectedeven if the other party already call shutdown(both) + close ,
sor , even if the other party close the app itslef.

Until there is no network I/O you can't get peer's socket state.

salso I determine different behaviour when my app running behind NAT
when I
srun behind NAT , calling to socket.Receive(..) throw exception which
was
sgood forme to determine that it's already closed the connection , it
sdoesn't throw nothing when I run the same code without NAT

When you're behind NAT, NAT server can detect peer state and send you
RST packet that will notify that socket is not connected anymore.

[skipped]

There are following ways how to resolve:
- use SocketOptionName.KeepAlive
- develop custom keep-alive mechanism.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com

Sep 21 '06 #2
Hello, semedao!

sSo... this method is something many developers need , there are noting
sin .NET that already do it ?

If you're using plain sockets you have to do it yourself.

In order to make keep-alives work, specify KeepAliveTime and KeepAliveInterval
under windows registry
( http://support.microsoft.com/default...b;en-us;158474 ).
Computer restart may be required.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Sep 21 '06 #3
In article <OD**************@TK2MSFTNGP02.phx.gbl>, Semedao wrote:
So... this method is something many developers need , there are noting in
..NET that already do it ?
Semedao,

It's one of those yes and no situations. The Socket.Connected property tells
you if the local socket knows it's connected to the other end.
Unfortunately, the socket doesn't always know if it's connected due to the
way the TCP protocol is designed. The socket also only updates its
open/closed state when a Send or Receive operation is performed (see
http://windowssdk.msdn.microsoft.com...sockets.socket
_members.aspx). If you search this newsgroup, you'll find many threads
addressing this isuue.

Mike

Sep 24 '06 #4
Hi,
This is Charles from Microsoft Online Community Support. For this issue, I
noticed that Vadym and Mike had given you explanations. I think the replies
are reasonable. If you wanted to know exactly the connection status, I'm
afraid that you need to judge according to socket exception when you send
or receive data on the socket.

Could you please let me know the issue status and if you need further
research? If you have any other questions or concerns, please feel free to
let me know. It's my pleasure to be of assistance.

Sincerely,
Charles Wang
Microsoft Online Community Support

Sep 28 '06 #5
I understand this issue , so the only way is to inherit the socket and
override the send & receive method to throw some event of
connected/disconnected
thanks
"Charles Wang[MSFT]" <ch******@online.microsoft.comwrote in message
news:cV**************@TK2MSFTNGXA01.phx.gbl...
Hi,
This is Charles from Microsoft Online Community Support. For this issue, I
noticed that Vadym and Mike had given you explanations. I think the
replies
are reasonable. If you wanted to know exactly the connection status, I'm
afraid that you need to judge according to socket exception when you send
or receive data on the socket.

Could you please let me know the issue status and if you need further
research? If you have any other questions or concerns, please feel free to
let me know. It's my pleasure to be of assistance.

Sincerely,
Charles Wang
Microsoft Online Community Support

Sep 29 '06 #6
Hi,
Appreciate your understanding and updating on this issue.

If you have any other questions or concerns, please feel free to let me
know. It's always my pleasure to be of assistance.

Sincerely,
Charles Wang
Microsoft Online Community Suppport

Sep 30 '06 #7
In article <e5**************@TK2MSFTNGP04.phx.gbl>, Semedao wrote:
so the only way is to inherit the socket and
override the send & receive method to throw some event of
connected/disconnected
You don't need to override the Send and Receive methods to have errors
reported as events. The base methods already raise socket exceptions
(etc.). What you do want to do is to ensure that your application has
a receive outstanding when you want to detect problems. When a simple,
synchronous (server) application has finished processing one request,
it naturally uses the Receive mthod to get the next request so error
exceptions are raised at this point.

Mike

Oct 1 '06 #8

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

Similar topics

4
by: DreJoh | last post by:
I've read many articles on the subject and the majority of them give the same solution that's in article 821625 on the MSDN website. I'm using the following code and when a the client disconnects...
1
by: Dr. J | last post by:
I have an application that opens a socket and connects to another application listening over a port. The problem I am encountering is that when the listening application is closed my application...
2
by: Nuno Magalhaes | last post by:
socket.Connected only gives the last access result but not the current status of the socket. What is the best way to determine if a socket is still connected? Because I want to cancel all my...
3
by: Cheryl | last post by:
Hi. I am having a problem on handling asynchronous sockets in C#. I implemented a pair of client and server sockets. The connection is ok when first connected. However, when I turned off the...
3
by: Giampaolo Rodola' | last post by:
Hi there, since the socket.socket.family attribute has been introduced only in Python 2.5 and I need to have my application to be backward compatible with Python 2.3 and 2.4 I'd like to know how...
3
by: A. W. Dunstan | last post by:
I'm creating a socket as follows: m_networkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_networkSocket.LingerState = new LingerOption(true, 1);...
2
emibt08
by: emibt08 | last post by:
Hi. I have an array of sockets in my application and i need to know which sockets are connected and which ones aren't. In order to do that i check if the socket equals INVALID_SOCKET or NULL, but i...
3
by: StevenBlake | last post by:
Hi, I have developed a C# application which sends the data to the connected client. I am using TCP/IP protocol. The client connects with my application using 'Telnet command' through command...
2
by: kashifjawed | last post by:
I'm developing a c# asynchronous socket application for tranfering file or large data from client to server and server to client as well in chunks. Application sometimes transfer file from client...
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: 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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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?
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...

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.