WebClient.java
2.92 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.huaheng.mobilewms.service;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by youjie on 2021/2/24
*/
public class WebClient extends WebSocketClient{
public static final String ACTION_RECEIVE_MESSAGE = "com.jinuo.mhwang.servermanager";
public static final String KEY_RECEIVED_DATA = "data";
private static WebClient mWebClient;
private Context mContext;
/**
* 路径为ws+服务器地址+服务器端设置的子路径+参数(这里对应服务器端机器编号为参数)
* 如果服务器端为https的,则前缀的ws则变为wss
*/
// private static final String mAddress = "ws://172.16.27.212:8888/wms/websocket/";
private static final String mAddress = "ws://172.16.27.212:8888/wms/websocket/2";
private static void showLog(String msg){
Log.d("WMSLog", msg);
}
private WebClient(URI serverUri, Context context){
super(serverUri, new Draft_6455());
mContext = context;
showLog("WebClient");
}
@Override
public void onOpen(ServerHandshake handshakedata) {
showLog("open->"+handshakedata.toString());
}
@Override
public void onMessage(String message) {
showLog("onMessage->"+message);
sendMessageBroadcast(message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
showLog("onClose->"+reason);
}
@Override
public void onError(Exception ex) {
showLog("onError->"+ex.toString());
}
/** 初始化
* @param vmc_no
*/
public static void initWebSocket(final Context context, final long vmc_no){
new Thread(new Runnable() {
@Override
public void run() {
try {
mWebClient = new WebClient(new URI(mAddress), context);
try {
boolean success = mWebClient.connectBlocking();
showLog("connectBlocking->"+ success);
} catch (Exception e) {
e.printStackTrace();
showLog("connectBlocking->"+ e.getMessage());
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}).start();
}
/** 发送消息广播
* @param message
*/
private void sendMessageBroadcast(String message){
if (!message.isEmpty()){
Intent intent = new Intent();
intent.setAction(ACTION_RECEIVE_MESSAGE);
intent.putExtra(KEY_RECEIVED_DATA,message);
showLog("发送收到的消息");
mContext.sendBroadcast(intent);
}
}
}