Android WebSocket长连接

1.build.gradle中添加依赖:

implementation "org.java-websocket:Java-WebSocket:1.5.1"

2.在清单文件中加入网络请求权限:

 <uses-permission android:name="android.permission.INTERNET" />

3.需要在AndroidManifest.xml中开启一个服务:

<!-- 后台服务-长连接 -->
<service android:name=".service.MyService" />

写一个类MyService继承Service,在onCreate()方法中开启一个线程。

public class MyService extends Service {
    
    

    //WebSocket长连接
    public Application application;

    public Context context;

    boolean isSuccess;
    private long sendTime = 0L;
    


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    
    
        return null;
    }

    //
    private WebSocketThread thread;
                                             

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        if (mWebSocket != null) {
    
    
            mWebSocket.close(1000, null);
        }

        new WebSocketThread().start();
        application= AndroidApp.getInstance();//这个是application,需要在功能清单里面的--android:name=".AndroidApp"
        context=AndroidApp.getInstance();
        Log.e("TAG", "onCreate------------*************-------------");                               
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
        return super.onStartCommand(intent, flags, startId);

    }


    /**
     * 心跳检测时间
     */
    private static final long HEART_BEAT_RATE = 10000;//每隔10秒进行一次对长连接的心跳检测
    private final String WEBSOCKET_HOST_AND_PORT = "ws://";//可替换为自己的主机名和端口号
    private static WebSocket mWebSocket;

    // 初始化WebSocket
    private void initSocket() throws UnknownHostException, IOException {
    
    
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url(WEBSOCKET_HOST_AND_PORT).build();
        client.newWebSocket(request, new WebSocketListener() {
    
    
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
    
    //开启长连接成功的回调
                super.onOpen(webSocket, response);
                mWebSocket = webSocket;
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
    
    //接收消息的回调
                super.onMessage(webSocket, text);
                //收到服务器端传过来的消息text             
                Log.e("TAG", "接收消息的回调--------------" + text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
    
    
                super.onMessage(webSocket, bytes);

            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
    
    
                super.onClosing(webSocket, code, reason);

            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
    
    
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
    
    //长连接连接失败的回调
                super.onFailure(webSocket, t, response);
            }
        });

        client.dispatcher().executorService().shutdown();
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
    }


    class WebSocketThread extends Thread {
    
    
        @Override
        public void run() {
    
    
            super.run();
            try {
    
    
                initSocket();
            } catch (UnknownHostException e) {
    
    
                e.printStackTrace();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }


    // 发送心跳包
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
    
    
        @Override
        public void run() {
    
    
           if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
    
    
                if (mWebSocket != null) {
    
    
                    boolean isSuccess = mWebSocket.send("自定义发给后台服务器的消息");//发送一个消息给服务器,通过发送消息的成功失败来判断长连接的连接状态
                    if (!isSuccess) {
    
    //长连接已断开,
                        mHandler.removeCallbacks(heartBeatRunnable);
                        mWebSocket.cancel();//取消掉以前的长连接
                        new WebSocketThread().start();//创建一个新的连接
                    } else {
    
    //长连接处于连接状态---
                        Log.e("TAG", "发送心跳包-------------长连接处于连接状态");
                    }
                }
                sendTime = System.currentTimeMillis();
            }
            mHandler.postDelayed(this, HEART_BEAT_RATE);//每隔一定的时间,对长连接进行一次心跳检测
        }
    };

    //关闭长连接
    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        if (mWebSocket != null) {
    
    
            mWebSocket.close(1000, null);
        }
    }
}

在你需要长连接的地方,开启长连接:

public class MainActivity extends BaseActivity {
    
    

    @Override
     protected void onCreate(Bundle savedInstanceState) {
    
    
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         //开启长连接
         startService();
         //关闭长连接
         //stopService();
     }

    private void startService() {
    
    
        Intent intent1 = new Intent(MainActivity.this, MyService.class);
	startService(intent1);
    }


//    private void stopService() {
    
    
//        Intent intent1 = new Intent(MainActivity.this, MyService.class);
//        stopService(intent1);
//    }
}

猜你喜欢

转载自blog.csdn.net/weixin_58159075/article/details/124345206