设备重启时如何重新连接TCP连接

时间:2019-04-19 09:39:35

标签: c# android tcp

这是Android与PC之间的通讯问题。 智能手机是主机,正在等待连接,当连接了PC时,智能手机将继续向PC发送信息。

即使智能手机重启,我也想重新连接TCP。即使重启后,智能手机仍在等待再次连接。如果智能手机已关闭,则连接的值仍为“ true”。并获得“空”值。 我应该怎么做才能再次连接?`

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连接。

1 个答案:

答案 0 :(得分:0)

只要我知道,您就必须同时为客户端和服务器配置ReceiveTimeout。

使用套接字将为您提供更多选择,例如

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