Android长连接 WebSocketClient请求WSS Websocke长连接

这个月才写了两篇博客,总觉得应该写一点什么,经过一系列的纠结还是给大家分享Android中一个简单的长连接方式吧,就是这玩意WebSocketClient;

一开始在进行WSS请求时直接进入onClose(),如wss://127.0.0.1:8080地址,直接拿WebSocket 在线测试又没有问题,这就纳闷了,经过一番搜索,网上说需要ssl校验证书,可一问后台哥们又说不需要。最后发现这么一篇文章,哟西,管他三七二一,先copy下来能用再说。结果还真没让人失望,成功哪能那容易呢,继续摆一把度娘发现,原来需要这玩意:

            SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) {

				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) {

				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			SSLSocketFactory factory = sslContext.getSocketFactory();

使用流程

1、下载Java-WebSocket-1.3.1.jar,点我下载==OK?OK:点我试试,下载完成导入开发工具即可,AS直接添加依赖即可;

2、完整代码

public void linkSocket(String url) {
		try {
			client = new WebSocketClient(new URI(url), new Draft_17()) {
				@Override
				public void onOpen(ServerHandshake handshakedata) {
					Log.e("onOpen:", "------连接成功!!!");
				}

				@Override
				public void onMessage(String message) {
					Log.e("onMessage:", message);

				}

				@Override
				public void onClose(int code, String reason, boolean remote) {
					Log.e("onClose:", "------连接关闭!!!" + reason);
				}

				@Override
				public void onError(Exception ex) {
					Log.e("onError:", ex.toString());
				}
			};
			// wss需添加
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) {

				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) {

				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			SSLSocketFactory factory = sslContext.getSocketFactory();
			client.setSocket(factory.createSocket());
			client.connect();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

添加完成运行,进入onOpen()说明连接成功,那如何来保活连接呢,定时发送消息来进行保活即可了,如:

/**
	 * 发送消息
	 * 
	 * @param msg
	 */
	public void sendMsg(String msg) {
		if (client != null) {
			client.send(msg);
		} else {
			closeConnect();
			linkSocket(ip);
		}
	}

OK到这里就结束了,如有不当联系修改,不吝指教,欢迎留言小菜我“玉念聿辉”。

编辑:吴明辉

没有更多推荐了,返回首页