基于WS协议的webSocket通信

使用的是java-webSocket

github地址:https://github.com/TooTallNate/Java-WebSocket

客户端

private final ExecutorService executorService = Executors.newSingleThreadExecutor();
 
private void socketConnect() {
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            Map headers = new HashMap();
            webSocketClient = new WebSocketClient(URI.create("ws://xxx.xxx.104.109:xxxx/"), new Draft_17(), headers, 10) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    
                }

                @Override
                public void onMessage(String message) {
                    SocketTypeInfo socketTypeInfo = GsonUtil.parseJsonWithGson(message, SocketTypeInfo.class);
                    if (socketTypeInfo != null) {
                        BindScoketInfo bindScoketInfo = GsonUtil.parseHeaderJsonWithGson(message, BindScoketInfo.class);
                        if (bindScoketInfo != null) {
                            if ("init".equals(socketTypeInfo.type)) {
                                bindSocket(bindScoketInfo.client_id);
                            } else {
                                int value = bindScoketInfo.value;
                                Message msg = mHandler.obtainMessage();
                                msg.what = 1;
                                msg.obj = value;
                                mHandler.sendMessage(msg);
                            }
                        }
                    }
                    
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    
                }

                @Override
                public void onError(Exception ex) {
                }
            };
            Log.i("huang", "after---");
            webSocketClient.connect();
        }
    });
}
 

webserver:

基于WS协议的webSocket通信_第1张图片

简单粗暴!

你可能感兴趣的:(Android)