Websocket在Android平台的消息推送上的应用

文章目录

  • 写在前面
  • Websocket Server
  • WebSocket Client
  • 效果展示
  • 源码下载

写在前面

之前接触过一个Android小项目,其中有个功能是服务端将文件推送到客户端,那时候,是通过客户端的轮询去询问是否有文件推送,如果有,则进行文件下载。其实,这种做法不可取,可以用Websocket来实现一个简单的消息推送系统,用于替代轮询。

Websocket Server

在这个 server demo中,使用的是GitHub上面的一个开源项目Java-WebSocket

  • 在AndroidStudio中添加依赖:

    implementation ‘org.java-websocket:Java-WebSocket:1.3.9’

  • 创建Server类:

    public class WsServer extends WebSocketServer {
    
        public WsServer(int port, SSLContext sslContext) {
            super(new InetSocketAddress(port));
            this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
        }
    
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            //This method sends a message to the new client
            conn.send("Welcome to the server!");
            broadcast("new connection: "
                    + handshake.getResourceDescriptor()); //This method sends a message to all
            // clients connected
            System.out.println(
                    conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
        }
    
        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            broadcast(conn + " has left the room!");
            System.out.println(conn + " has left the room!");
        }
    
        @Override
        public void onMessage(WebSocket conn, String message) {
            broadcast(message);
            System.out.println(conn + ": " + message);
        }
    
        @Override
        public void onMessage(WebSocket conn, ByteBuffer message) {
            broadcast(message.array());
            System.out.println(conn + ": " + message);
        }
    
        @Override
        public void onError(WebSocket conn, Exception ex) {
            ex.printStackTrace();
            if (conn != null) {
                // some errors like port binding failed may not be assignable to a specific websocket
            }
        }
    
        @Override
        public void onStart() {
            System.out.println("Server started!");
            setConnectionLostTimeout(0);
            setConnectionLostTimeout(100);
        }
    }
    
  • 开启Websocket Server

      private void startServer() {
        if (mWsServer != null) {
            try {
                mWsServer.stop();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        mWsServer = new WsServer(8888, makeSSLContext());
        mWsServer.start();
    }
    

WebSocket Client

客户端的实现,可以直接使用Java-WebSocket库的Client,可以参考这个项目中的examples,但在本示例中,我是使用OkHttp的Websocket来实现客户端。

  • 创建客户端项目,并依赖OkHttp

  • 创建OKHttpClient

    private void initClient() {
            CustomTrust ct = new CustomTrust();
            client = new OkHttpClient.Builder()
                    .sslSocketFactory(ct.sslSocketFactory, ct.trustManager)
                    .hostnameVerifier(hostnameVerifier)
                    .build();
        }
    
  • 连接远端服务器

     private void connectWs() {
            if (mWebSocket != null) {
                mWebSocket.cancel();
                mListener = null;
            }
            Request.Builder builder = new Request.Builder();
            // wss : support ssl
            // Both server and client can run in a same device, so the ip can be set to localhost
            builder.url("wss://localhost:8888");
            Request request = builder.build();
            mListener = new WsSocketListener();
            mWebSocket = client.newWebSocket(request, mListener);
        }
    

效果展示

Websocket在Android平台的消息推送上的应用_第1张图片

源码下载

源码下载

你可能感兴趣的:(android开发笔记)