How to tell when socket is disconnected
-
Hi, I'm working on a very simple socket communication program. It needs to connect, send a string, and disconnect. However, I need to know if the connect is terminated by the remote client before I try to disconnect (this is a requirement of the remote client software before my code is "certified"). I have the following code:
EndPoint ep = new IPEndPoint(IPAddress.Parse(sServerIP), iPort); Socket sockBatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); sockBatch.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 30000); sockBatch.Connect(ep); if (sockBatch.Connected) { Encoding ASCII = Encoding.ASCII; Byte[] byteDataLine = Encoding.ASCII.GetBytes(sSendData.ToCharArray()); sockBatch.Send( byteDataLine, byteDataLine.Length, 0 ); Byte[] RecvBytes = new Byte[256]; Int32 bytes = sockBatch.Receive(RecvBytes, RecvBytes.Length, 0); StringBuilder sbResponse = new StringBuilder(); sbResponse.Append(ASCII.GetString(RecvBytes, 0, bytes)); string sResponsePacket = string.Empty; while ((sockBatch.Connected) && (bytes > 0) && (-1 == sbResponse.ToString().IndexOf(sEndMarker))) { bytes = sockBatch.Receive(RecvBytes, RecvBytes.Length, 0); sResponsePacket = ASCII.GetString(RecvBytes, 0, bytes); sbResponse.Append(sResponsePacket); } } loggerBatch.Info("TEST DELAY before disconnect socket"); for (int iWait = 0; iWait < 1 * 60; iWait++) { Thread.Sleep(1000); } bool bPoll = sockBatch.Poll(10000, SelectMode.SelectWrite); loggerBatch.Info("Batch Socket Write poll: {0}", bPoll); bool bPoll1 = sockBatch.Poll(10000, SelectMode.SelectError); loggerBatch.Info("Batch Socket Error poll: {0}", bPoll1); loggerBatch.Info("Batch Socket is connected: {0}", sockBatch.Connected); if (bPoll && sockBatch.Connected) { loggerBatch.Info("Poll says connected"); try { byteDataLine = Encoding.ASCII.GetBytes("AYT".ToCharArray()); sockBatch.Send( byteDataLine, byteDataLine.Length, 0 ); } catch (Exception ex) { logger.Info("AYT Error: {0}", ex.ToString()); } loggerBatch.Info("Disconnect from socket"); sockBatch.Shutdown(SocketShutdown.Both); sockBatch.Close(); } else { loggerBatch.Info("Socket was disconnected."); }
Output of above2006-06-16 10:19:59.7241|INFO|batch|TEST DELAY before disconnect socket 2006-06-16 10:20:59.7233|INFO|batch|Batch Socket Write poll: True 2006-06-16 10:20:59.7390|INFO|batch|Batch Socket Error