简体   繁体   中英

Poll a connected client from a server in C#

I am trying to poll a connection from a client connected to my server.

When you use poll you need to give it a socket connection but on the server's side the socket is bound to it's own IP address and a specific port. Making another socket to connect on the same port but with the client's IP address won't work since you can't have multiple connections on the same socket.

I am just wondering what would be a good way to constantly be checking if a client is still connected to the server and also when it disconnects?

I was thinking some sort of timeout check or something. I just wanted to know if there was any generic or proper way of achieving this.

I have tried Socket.Poll but it does not seem to achieve what I want.

To restate my question, how do you check if a client is connected on the server side using TCP sockets in C#?

socket.Receive will just return 0. From MSDN

If you are using a connection-oriented Socket, the Receive method will read as much data as is available, up to the size of the buffer. If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

There is also Connected property in the Socket class if you need.

There are two kinds of sockets: For listening and for connections. If a client has connected you must have an instance of Socket that is associated with that connection.

Use this socket to periodically send data and receive and acknowledgement back. This is the only way to make 100% sure that the connection is still open.

Especially the Connected property cannot be used to detect a lost connection because if the network cable is unplugged neither of the two parties is notified in any way. The property can't be accurate by principle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM