最近在做使用三方im做一些業(yè)務(wù)的時候,領(lǐng)導(dǎo)覺得三方的im通信并不能很好的適應(yīng)我們的需求隘擎。
所以決定抽時間性宏,自己使用WebSocket實(shí)現(xiàn)一個長鏈接群井。
做之前肯定要逛一逛github,學(xué)習(xí)一下優(yōu)秀的經(jīng)驗(yàn)贷掖,不經(jīng)意間就找到了 Java-WebSocket刑赶,秉著這不重復(fù)制造輪的理論锯厢,直接上手使用起來谆膳。
Gradle 使用
mavenCentral()
implementation 'org.java-websocket:Java-WebSocket:1.5.1'
創(chuàng)建WebSocketChatClient繼承WebSocketClient
public class WebSocketChatClient extends WebSocketClient {
public WebSocketChatClient(URI serverUri) {
super(serverUri);
}
public WebSocketChatClient(URI serverUri, Draft draft) {
super(serverUri, draft);
}
public WebSocketChatClient(URI serverUri, Map<String, String> httpHeaders) {
super(serverUri, httpHeaders);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("WebSocketChatClient Connected");
}
@Override
public void onMessage(String message) {
System.out.println("WebSocketChatClient got: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("WebSocketChatClient Disconnected");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
System.out.println("WebSocketChatClient onError");
}
}
然后初始化WebSocketChatClient
var str: String? =
"ws://robot-app.wondertemple.com:8058/4419a2e94b2b9cd2bde7f8103dfa5b25"
var chatClient: WebSocketChatClient? = null
chatClient = WebSocketChatClient(URI(str))
chatClient?.connect()
鏈接成功叭爱,后臺返回
com.example.socketdemo I/System.out: WebSocketChatClient Connected
com.example.socketdemo I/System.out: WebSocketChatClient got: {"cmd":"connection","data":{"message":"ok"}}
斷開連接
chatClient?.close()
重連
chatClient?.reconnect()
發(fā)送消息
chatClient?.send(JSONObject.toJSONString(msgBean))
至此,一個簡單的im 基礎(chǔ)功能就完成了漱病,后邊大家就可以慢慢擴(kuò)展了