Android signalr

650 阅读1分钟

添加依赖

//websocket
implementation 'org.java-websocket:Java-WebSocket:1.3.6'
implementation 'com.microsoft.signalr:signalr:3.0.0'
//messagepack
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) {
//                    Log.e(TAG,"param:" + obj.toString());
                }
            }
            hubConnection.send(method, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if(hubConnection.getConnectionState()== HubConnectionState.CONNECTED){
            hubConnection.stop();
        }
    }
}