首先,我对网络连接还很陌生,所以请不要对我不礼貌。 我的Tcp连接有问题。每当我的设备进入休眠模式(屏幕关闭)时,它不会定期(每5秒发送一次)发送心跳,因此我的服务器认为连接丢失并重新启动。我在这里想念什么?
我注意到,如果没有心跳到达服务器端,则每次我再次打开它时,都会同时到达多个心跳。
我用C#编写了一个服务器,该服务器接受客户端并每10秒检查一次是否发送了来自客户端的心跳。如果没有,他将断开连接。
public static void startServer(MainWindow mw)
{
//Create Tcp connection
TcpListener server = new TcpListener(IPAddress.Parse("192.168.192.22"), 8001);
server.Start();
//Wait for client
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[1];
//keepAlive (first time NOW)
long lastKeepAlive = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
while (true)
{
if (stream.DataAvailable)
{
var readByteCount = stream.Read(bytes, 0, bytes.Length);
if (readByteCount > 0)
{
lastKeepAlive = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
var incommingData = new byte[readByteCount];
Array.Copy(bytes, 0, incommingData, 0, readByteCount);
string serverMessage = Encoding.ASCII.GetString(incommingData);
Console.Write(serverMessage);
}
}
//If 10 seconds are over drop connection and start again
if (((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - lastKeepAlive) > 10000)
{
server.Stop();
client.Close();
startServer(mw);
break;
}
}
}
我的android应用程序是客户端。我使用NotificationListener,所以我认为可以使用此服务而不是使用额外的服务,因此我将在后台运行。我通过gui(广播)启动此方法。
public void startClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
client = new Socket();
client.connect(new InetSocketAddress("192.168.192.22", 8001), 1000);
client.setTcpNoDelay(true);
client.setKeepAlive(true);
client.setSoTimeout(200);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
//Send heartbeat each 5 seconds
task = new Timer();
task.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
keepAlive();
}
}, 5000, 5000);//put here time 5000 milliseconds=5 second
}
catch (SocketTimeoutException e){
Thread.currentThread().interrupt();
return;
} catch (IOException e) {
Log.e("error","No I/O");
}
}
}).start();
}