TcpClient 自动重新连接
使 Tcpclient 自动重新连接到服务器的最佳方法是什么 它已断开连接(例如由服务器本身断开连接)?
我当前使用的代码是:
public void ClientWork()
{
TcpClient client = new TcpClient();
try
{
try
{
client.Connect(ip, port);
}
catch(Exception ex)
{
logger.ErrorFormat("client.Connect: {0}", ex.Message);
return false;
}
NetworkStream ns = client.GetStream();
byte[] buff;
while (__bRunning)
{
buff = new byte[1000];
ns.Read(buff, 0, 1000);
string line = System.Text.Encoding.Default.GetString(buff);
}
//ns.Close();
client.Close();
}
catch(Exception e)
{
//Reconnect?
client.Close();
client = null;
return false;
}
}
我正在使用 C# .NET
What is the best way to make a Tcpclient auto reconnect to the server when
it's disconnected (e.g. by the server itself)?
The code I'm currently using is:
public void ClientWork()
{
TcpClient client = new TcpClient();
try
{
try
{
client.Connect(ip, port);
}
catch(Exception ex)
{
logger.ErrorFormat("client.Connect: {0}", ex.Message);
return false;
}
NetworkStream ns = client.GetStream();
byte[] buff;
while (__bRunning)
{
buff = new byte[1000];
ns.Read(buff, 0, 1000);
string line = System.Text.Encoding.Default.GetString(buff);
}
//ns.Close();
client.Close();
}
catch(Exception e)
{
//Reconnect?
client.Close();
client = null;
return false;
}
}
I'm using C# .NET
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有可用于获取连接断开通知的事件。
可能有 2 种可能的解决方案。
投票。您有单独的线程尝试在不同的线程中不断轮询套接字。请参阅立即检测客户端与服务器套接字的断开
如果您有对套接字或使用套接字的接口的低级别控制,您可以对读写方法执行 try..catch 或对读写方法的包装器执行 try..catch ,当出现任何异常时,您可以重新连接并尝试阅读和写作。
There is no events available to get notification for broken connection.
There could be 2 possible solution.
Polling. You have separate thread that try to poll socket continually done in different thread. Refer Instantly detect client disconnection from server socket
If you have low level control over socket or the interface which is using socket, you can do try..catch for read and write methods or try..catch for wrappers of read and write methods and when there is any exception you can re-connect and try to read and write.