关于WebSocket简介见维基百科WebSocket。
在Android客户端,一般可以有两种方式实现WebSocket通信:
- 通过okhttp实现WebSocket通信
- Java-WebSocket,纯java实现的WebSocket通信
WebSocket可用于即时通信,直播弹幕等场景
本文只讲通过okhttp V3.6.0怎么实现WebSocket通信
首先导入依赖:compile 'com.squareup.okhttp3:okhttp:3.6.0'
然后是添加联网权限:
最后是具体代码实现:
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url("ws://" + "192.168.1.100" + ":" + 9555 + "/")
.build();
mWebSocket = okHttpClient.newWebSocket(request, new WebSocketListener() {
//创建线程池,
ExecutorService writeExecutor = Executors.newSingleThreadExecutor();
WebSocket webSocket = null;
@Override
public void onOpen(final WebSocket webSocket, final Response response) {
this.webSocket = webSocket;
//建立连接成功后,发送消息给服务器端
writeExecutor.execute(new Runnable() {
@Override
public void run() {
//socket 发送信息到服务器
webSocket.send(“连接成功后,第一次发送信息”);
}
});
}
@Override
public void onMessage(final WebSocket webSocket, String text) {
//获取到服务器发送过来的信息,然后通过handler进行UI线程的操作
Message message = Message.obtain();
message.what = READ_BYSOKET;
message.obj = text;
mHandler.sendMessage(message);
}
//webSocket关闭时,关闭线程池
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
writeExecutor.shutdown();
}
});
最后通过mWebSocket.cancel();
将WebSocket关闭。