首页 > 解决方案 > 设备重启时如何重新连接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 连接。

标签: c#androidtcp

解决方案


据我所知,您必须为客户端和服务器配置 ReceiveTimeout。

并且使用 socket 会给你更多的选择,比如

SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true)。


推荐阅读