博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android 心跳长链接,Android socket通讯的长链接与心跳检测
阅读量:5934 次
发布时间:2019-06-19

本文共 4126 字,大约阅读时间需要 13 分钟。

package com.example.sockettest;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.lang.ref.WeakReference;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Arrays;

import android.annotation.SuppressLint;

import android.app.Service;

import android.content.Intent;

import android.os.Handler;

import android.os.IBinder;

import android.os.RemoteException;

import android.util.Log;

public class BackService extends Service {

private static final String TAG = "BackService";

/** 心跳检测时间 */

private static final long HEART_BEAT_RATE = 3 * 1000;

/** 主机IP地址 */

private static final String HOST = "192.168.1.104";

/** 端口号 */

public static final int PORT = 9800;

/** 消息广播 */

public static final String MESSAGE_ACTION = "org.feng.message_ACTION";

/** 心跳广播 */

public static final String HEART_BEAT_ACTION = "org.feng.heart_beat_ACTION";

private long sendTime = 0L;

/** 弱引用 在引用对象的同时容许对垃圾对象进行回收 */

private WeakReference mSocket;

private ReadThread mReadThread;

private IBackService.Stub iBackService = new IBackService.Stub() {

@Override

public boolean sendMessage(String message) throws RemoteException {

return sendMsg(message);

}

};

@Override

public IBinder onBind(Intent arg0) {

return (IBinder) iBackService;

}

@Override

public void onCreate() {

super.onCreate();

new InitSocketThread().start();

}

// 发送心跳包

private Handler mHandler = new Handler();

private Runnable heartBeatRunnable = new Runnable() {

@Override

public void run() {

if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {

boolean isSuccess = sendMsg("");// 就发送一个\r\n过去, 若是发送失败,就从新初始化一个socket

if (!isSuccess) {

mHandler.removeCallbacks(heartBeatRunnable);

mReadThread.release();

releaseLastSocket(mSocket);

new InitSocketThread().start();

}

}

mHandler.postDelayed(this, HEART_BEAT_RATE);

}

};

public boolean sendMsg(String msg) {

if (null == mSocket || null == mSocket.get()) {

return false;

}

Socket soc = mSocket.get();

try {

if (!soc.isClosed() && !soc.isOutputShutdown()) {

OutputStream os = soc.getOutputStream();

String message = msg + "\r\n";

os.write(message.getBytes());

os.flush();

sendTime = System.currentTimeMillis();// 每次发送成功数据,就改一下最后成功发送的时间,节省心跳间隔时间

Log.i(TAG, "发送成功的时间:" + sendTime);

} else {

return false;

}

} catch (IOException e) {

e.printStackTrace();

return false;

}

return true;

}

// 初始化socket

private void initSocket() throws UnknownHostException, IOException {

Socket socket = new Socket(HOST, PORT);

mSocket = new WeakReference(socket);

mReadThread = new ReadThread(socket);

mReadThread.start();

mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);// 初始化成功后,就准备发送心跳包

}

// 释放socket

private void releaseLastSocket(WeakReference mSocket) {

try {

if (null != mSocket) {

Socket sk = mSocket.get();

if (!sk.isClosed()) {

sk.close();

}

sk = null;

mSocket = null;

}

} catch (IOException e) {

e.printStackTrace();

}

}

class InitSocketThread extends Thread {

@Override

public void run() {

super.run();

try {

initSocket();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

public class ReadThread extends Thread {

private WeakReference mWeakSocket;

private boolean isStart = true;

public ReadThread(Socket socket) {

mWeakSocket = new WeakReference(socket);

}

public void release() {

isStart = false;

releaseLastSocket(mWeakSocket);

}

@SuppressLint("NewApi")

@Override

public void run() {

super.run();

Socket socket = mWeakSocket.get();

if (null != socket) {

try {

InputStream is = socket.getInputStream();

byte[] buffer = new byte[1024 * 4];

int length = 0;

while (!socket.isClosed() && !socket.isInputShutdown()

&& isStart && ((length = is.read(buffer)) != -1)) {

if (length > 0) {

String message = new String(Arrays.copyOf(buffer,

length)).trim();

Log.i(TAG, "收到服务器发送来的消息:"+message);

// 收到服务器过来的消息,就经过Broadcast发送出去

if (message.equals("ok")) {// 处理心跳回复

Intent intent = new Intent(HEART_BEAT_ACTION);

sendBroadcast(intent);

} else {

// 其余消息回复

Intent intent = new Intent(MESSAGE_ACTION);

intent.putExtra("message", message);

sendBroadcast(intent);

}

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

转载地址:http://tkctx.baihongyu.com/

你可能感兴趣的文章
golang通过反射动态调用方法
查看>>
Win10 UWP 开发系列:使用多语言工具包让应用支持多语言
查看>>
最简单易懂的SpringCloudSleuth教程
查看>>
【spring Boot】Spring中@Controller和@RestController之间的区别
查看>>
浪潮之巅——IT产业的三大定律
查看>>
Java并发编程:线程池的使用
查看>>
HttpMessageConverter 专题
查看>>
ssd运行过程中遇到的bug
查看>>
【NLP】Stanford
查看>>
【Python】Python中in与not in
查看>>
java io性能分析
查看>>
封装自己DB
查看>>
BZOJ4739 : 定向越野
查看>>
JSON的三种解析方式
查看>>
html5--2.10综合实例2-移动端页面练习
查看>>
adb安装启动Touch校正软件
查看>>
英语日常词汇:living-room、dining-room vs dining hall
查看>>
java线程-synchronized实现可见性代码
查看>>
javascript提取联通个人信息和通话记录的代码
查看>>
049——VUE中使用animation与transform实现vue的动画效果
查看>>