一:首先build.gradle集成
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
二:websocket代码
package com.xx.xx.websocket;
import androidx.annotation.Nullable;
import com.shuye.znsy.activity.MainActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class WebSocketExample {
private WebSocket webSocket;
private OkHttpClient client;
private MainActivity mainActivity;
public WebSocketExample(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
public void start() {
client = new OkHttpClient();
Request request = new Request.Builder()
.url("ws://192.168.100.11:8001/wss/notice.sc")
.build();
webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, okhttp3.Response response) {
// 连接打开时的回调
webSocket.send("连接已建立,你可以发送消息了。");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
// 接收到文本消息时的回调
System.out.println("接收到文本消息: " + text);
// 调用MainActivity的appUpdate方法
mainActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mainActivity.appUpdata();
}
});
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
// 接收到二进制消息时的回调
System.out.println("接收到二进制消息: " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
// 即将关闭连接时的回调
webSocket.close(1000, "关闭连接");
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
// 连接失败时的回调
t.printStackTrace();
}
});
}
public void stop() {
if (webSocket != null) {
webSocket.close(1000, "正常关闭");
}
}
}
三:
MainActivity主类调用
protected void onCreate(Bundle savedInstanceState) {
//其他代码
WebSocketExample webSocketExample = new WebSocketExample(this);
webSocketExample.start();
}