c# - 设备重启时如何重新连接tcp连接
问题描述
这是Android和PC之间的通信问题。智能手机是主机,等待连接,当电脑连接好后,智能手机继续向电脑发送信息。
即使智能手机重新启动,我也想重新连接 tcp。即使重新启动后,智能手机也在等待再次连接。如果智能手机关闭,连接的值仍然是“真”。并收到“空”值。这个时候我应该怎么做才能再次连接?`
TcpClient MyTcpClient;
int myPort = 4000;
StreamWriter MyWriter;
StreamReader MyReader;
int port = GetFreePort();
MyTcpClient = new TcpClient(IPAddress.Loopback.Tostring(), port);
MyTcpClient.ReceiveTimeout = 30000;
MyReader = new StreamReader(MyTcpClient.GetStream());
MyWriter = new StreamWriter(MyTcpClient.GetStream());
while(MyTcpClient.Connected) //if device is off, it still true
{
string line = MyReader.ReadLine();// when device is off, it is null
}
如果设备重新启动,我想重新连接 Tcp 连接。
解决方案
据我所知,您必须为客户端和服务器配置 ReceiveTimeout。
并且使用 socket 会给你更多的选择,比如
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true)。
推荐阅读
- swift - 为什么似乎返回打印的函数声明为 Void?
- html - 我无法在此引号滑块上显示文本
- kubernetes - 在命名空间之间移动 pod
- regex - Groovy 中的正则表达式 - 仅在第一个下划线之前提取部分
- node.js - 什么是编译nodejs的好方法
- java - ImageIcon 方法无限循环
- python - 使用 unittest 检查“--help”标志输出
- c# - 在 xamarin 中使用参数将值绑定到函数
- linux - 如何在不搜索 .Trash 文件的情况下从 linux 终端找到 USB 上的文件?
- python - selenium.common.exceptions.InvalidArgumentException:消息:使用 Selenium Python 从文本文件读取的 URL 调用 get() 时参数无效错误