添加依赖
implementation 'org.java-websocket:Java-WebSocket:1.3.6'
implementation 'com.microsoft.signalr:signalr:3.0.0'
implementation 'com.microsoft.signalr.messagepack:signalr-messagepack:5.0.1'
代码示例
public class SampleClientTest {
private HubConnection hubConnection;
private String webSocket = "ws://192.168.0.197:5100/chathub";
private IClientTest iHrClient;
public SampleClientTest(IClientTest iHrClient) {
this.iHrClient =iHrClient;
hubConnection = HubConnectionBuilder.create(webSocket).build();
hubConnection.on("Test", (message) -> {
iHrClient.show("Test msg: " +message);
}, String.class);
hubConnection.onClosed(new OnClosedCallback() {
@Override
public void invoke(Exception exception) {
}
});
}
public void start(){
try {
hubConnection.start().blockingAwait();
iHrClient.show("ConnectionId "+hubConnection.getConnectionId());
} catch (Exception e) {
e.printStackTrace();
}
}
public void send(String method, Object... args) {
try {
if (args != null) {
for (Object obj : args) {
}
}
hubConnection.send(method, args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
if(hubConnection.getConnectionState()== HubConnectionState.CONNECTED){
hubConnection.stop();
}
}
}