如何使用tcpclient检测客户端与服务器的断开连接 [英] How to detect client disconnection from server using tcpclient

查看:1420
本文介绍了如何使用tcpclient检测客户端与服务器的断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个独立的应用程序Client和Server用于从以太网电缆发送和接收数据。客户端应用程序将数据发送到服务器。首先,当服务器应用程序启动时,它开始接受客户端请求以接受数据。客户端连接后,服务器线程就会立即从客户端接收数据。每当客户端应用程序停止时,必须向服务器发送一些命令以通知它已断开连接,或者必须有某种方法来检测服务器端的客户端断开连接,以便可以关闭线程以从客户端接收数据。我正在使用TCPClient来达到这个目的。请建议一些方法来做到这一点。

谢谢



我尝试过:



i我试图断开客户端与服务器的连接,但服务器仍然认为它已连接。

I have two separate applications Client and Server used to send and receive data from Ethernet Cable. The Client application sends the data to server. First when the server application is started, it starts accepting client request to accept data. As soon as client is connected , Server thread is started to receive data from Client. Whenever Client application is stopped, there must be either some command send to the server to notify that it has disconnected or there must be some way to detect client disconnection at server end so that thread can be closed for receiving data from Client. I am using TCPClient for this purpose. Kindly suggest some way to do this.
Thanks

What I have tried:

i am trying to disconnect a client from a server but the server still sees it as being connected.

推荐答案

参见 TcpClient.Connected属性(System.Net.Sockets) [ ^ ]


连接的每一端应在关闭连接时通知对方。



这必须在数据协议级别完成。例如,一方发送停止通信的请求,另一方通过确认响应发送请求。发送请求的一方在收到响应后关闭连接,另一方在响应发送后关闭连接。



要处理意外断开连接,请使用提供的功能。解决方案1由理查德。但请注意,这是返回最近操作的状态,通常不是实际状态。触发获取实际状态只是向另一方发送请求。这可能是一个特殊的请求,一定不能回答(NOOP / No Operation的kinf或保持活着)。如果另一方不再存在,发送请求将失败并且连接(和线程)可以关闭。
Each side of a connection should inform the other side when it closes the connection.

This must be done at data protocol level. For example one side sends a request to stop communication and the other answers with an acknowledge response. The side sending the request closes the connection when the response has been received and the other side after the response has been send.

To handle unexpected disconnections use the function provided in solution 1 by Richard. But note that that is returning the state of the most recent operation which is usually not the actual state. To trigger getting the actual state just send a request to the other side. This might be a special request that must not be answered (kinf of NOOP / No Operation or keep alive). If the other side is no longer present, sending the request will fail and the connection (and the thread) can be closed.


服务器在一段时间后丢弃连接时间,如果没有活动(超时)。



服务器不能依赖客户端关闭其连接,因为客户端可以在发送任何最后请求之前的任何给定时间死亡。
The "server" "drops" the connection after a period of time if no activity ("times out").

The "server" cannot depend on a client to close "its" connection, because the client(s) could "die" at any given time before having sent any "last requests".


这篇关于如何使用tcpclient检测客户端与服务器的断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆