android的websocket

本文最后更新于:2022年10月19日 晚上

android studio,websocket笔迹

Java-WebSocket

引入

Java-WebSocket

  • 在android studio中,点击文件->项目管理,然后如下图进行添加Java-WebSocket
    1
    org.java-websocket:Java-WebSocket:1.5.2

代码

myWebSocket.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.sonix.app;

import android.util.Log;
import java.net.URI;
import org.greenrobot.eventbus.EventBus;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sonix.util.Events;
import com.sonix.util.LogUtils;
import com.tqltech.tqlpencomm.bean.Dot;


public class MyWebsocket extends WebSocketClient{

public String TAG = "websocketClient";

public MyWebsocket(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.d(TAG, "client onOpen");
String message = "{\"type\":2}";
send(message);

}

@Override
public void onMessage(String message) {
Log.d(TAG, "client onMessage: " + message);
try {
JSONObject msg = new JSONObject(message);
String messageJson = msg.getString("message");
String codeJson = msg.getString("code");
if(messageJson.equals("测试")){
Log.d(TAG, "dot recv");
JSONObject data = msg.getJSONObject("data");
JSONObject pointsData = data.getJSONObject("pointsData");
JSONArray points = pointsData.getJSONArray("points");
JSONObject point = points.getJSONObject(0);
Dot dot = new Dot(
point.getInt("counter"),
Dot.DotType.valueOf(point.getString("type"))
);
LogUtils.d(TAG, "recv json: " + dot.toString());
}
else{
Log.d(TAG, "other msg");
}
}catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onClose(int code, String reason, boolean remote) {
Log.d(TAG, "client onClose");
}

@Override
public void onError(Exception ex) {
ex.printStackTrace();
// if the error is fatal then onClose will be called additionally
}

}

使用

1
2
3
4
5
6
7
8
9
10
11
12
MyWebsocket WsClient = null;

LogUtils.i(TAG,"websocket try connect");
String webSocketUrl = "wss://test.com";

try {
WsClient = new MyWebsocket(new URI(webSocketUrl));
}catch (Exception e){
e.printStackTrace();
}
WsClient.connect();

OKHTTP

引入

项目地址:GITHUB
引入方式还是在文件->项目结构中搜索

1
com.squareup.okhttp3:mockwebserver:4.9.3

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
OkHttpClient mClient = new OkHttpClient.Builder()
.pingInterval(10, TimeUnit.SECONDS)
.build();
//连接地址
String url = "wss://test:9403/";
//构建一个连接请求对象
Request request = new Request.Builder().get().url(url).build();

//开始连接
WebSocket websocket = mClient.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
Log.d("websocket", "onOpen");
boolean isSendSuccess = webSocket.send("{\"type\":2}");
Log.d("websocket", "send: "+isSendSuccess);
//连接成功...
}

@Override
public void onMessage(WebSocket webSocket, String text) {

super.onMessage(webSocket, text);
Log.i("websocket", "onMessage: " + text);
//收到消息...(一般是这里处理json)
try {
JSONObject msg = new JSONObject(text);
String messageJson = msg.getString("message");
String codeJson = msg.getString("code");

if(messageJson.equals("test")){
JSONObject data = msg.getJSONObject("data");
JSONObject pointsData = data.getJSONObject("pointsData");

JSONArray points = pointsData.getJSONArray("points");

//for(int i = 0; i < points.length(); i++){
JSONObject point = points.getJSONObject(0);
Dot dot = new Dot(
point.getInt("counter"),
Dot.DotType.valueOf(point.getString("type"))
);
//LogUtils.d(TAG, "recv json: " + dot.toString());
//}
EventBus.getDefault().post(new Events.ReceiveDot(dot,true));

}
else if(messageJson.equals("pong")){
Log.d(TAG, "pong recv");
}
else{
Log.d(TAG, "other msg");
}
}catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
//收到消息...(一般很少这种消息)
}

@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
//连接关闭...
}

@Override
public void onFailure(WebSocket webSocket, Throwable throwable, Response response) {
super.onFailure(webSocket, throwable, response);
//连接失败...
Log.e("websocket", "onFailure: " + throwable.getMessage());
}
});