At first, using the connected property of the socket class to implement, but found that it does not work, connected only to indicate whether the last or the operation of the connection to the remote host. If after that [the other side of the connection] is disconnected, it also always returns true unless you send the data through the socket again. So it's impossible to judge by a property!
Later, it was said that the socket.available attribute can be used to judge that socket.available represents the amount of data that has been received from the network and available for reading.
MSDN says: If the [Other side of the connection] is disconnected, it throws an exception. However, this bug report (http://dam.mellis.org/2004/08/net_socket_bugs_gotchas/) points out that MSDN is not entirely correct, and this property only throws exceptions in a few cases. So, this trick still won't work!
Finally, the socket is used. Poll () method to complete the implementation, this method is to determine the state of the socket. Look at the following code:
Service-Side code:
classProgram {Private StaticList<socket> list=NewList<socket>(); Static voidMain (string[] args) {Timer Timer=NewTimer ( +); Timer. Elapsed+=NewElapsedeventhandler (timer_elapsed); Timer. Start (); Thread Thread=NewThread (Listener); Thread. Start (); } //server-to-Client push per second Static voidTimer_elapsed (Objectsender, Elapsedeventargs e) { if(list. Count >0) { for(inti = list. count-1; I >=0; i--) { stringSendstr ="Server Information"; byte[] bs =Encoding.ASCII.GetBytes (SENDSTR); if(List[i]. Poll ( +, Selectmode.selectread))//Selectmode.selectread indicates true if it has been called and has a pending connection. -or-if the data is available for reading;true。 -or-If the connection is closed, reset, or terminated, returnstrue(This means that if the client disconnects, this method returns True);false. {List[i]. Close ();//Close SocketList. RemoveAt (i);//remove a broken Socke from the list Continue; } List[i]. Send (BS, BS. Length,0); } } } Public Static voidListener () {intPort =11000; stringHost ="192.168.7.36"; /**/ ///Create an endpoint (EndPoint)IPAddress IP = ipaddress.parse (host);//Convert an IP address string to an instance of the IPAddress typeIPEndPoint ipe =NewIPEndPoint (IP, port);//Initializes a new instance of the IPEndPoint class with the specified port and IP /**/ ///Create a socket and start listeningSocket s =NewSockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);//Create a socket pair image, if using the UDP protocol, use the Sockettype.dgram type socketS.bind (IPE);//bind endpoint to (2000 port and IP address)S.listen (Ten);//Start listening .Console.WriteLine ("Waiting for client connections"); while(true) { /**/ ///Accept the client connection, create a new socket for this connection, and accept the informationlist. ADD (S.accept ());//create a new socket for a new connectionConsole.WriteLine ("Establish a connection"); stringRecvstr =""; byte[] Recvbytes =New byte[1024x768]; intbytes; Bytes= List[list. count-1]. Receive (Recvbytes, Recvbytes.length,0);//receiving information from the clientRecvstr + = Encoding.ASCII.GetString (Recvbytes,0, bytes); /**/ ///return information to client sideConsole.WriteLine ("server Get message:{0}", RECVSTR);//to show the message from the client. stringSendstr ="ok! Client Send Message successful!"; byte[] bs =Encoding.ASCII.GetBytes (SENDSTR); List[list. Count-1]. Send (BS, BS. Length,0);//return information to the client//temp. Close ();} s.close (); } }
Transferred from: http://hi.baidu.com/jack1865/item/3dcba2d3b0e2e29932db904d
C # Server method for determining whether a client socket has been disconnected