Websocket onMessage中的android回调接口

时间:2016-11-14 06:03:45

标签: java android websocket

我正在尝试为websocket send创建库。

public class SocketCls {
    private WebSocketClient mWebSocketClient;
    private void connectWebSocket(String url) throws URISyntaxException {
        URI uri;
        uri = new URI(url);

        mWebSocketClient = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                Log.i("Websocket", "Opened");
                mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            }

            @Override
            public void onMessage(String s) {
                final String message = s;
              // Here i want to use callback
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                Log.i("Websocket", "Closed " + s);
            }

            @Override
            public void onError(Exception e) {
                Log.i("Websocket", "Error " + e.getMessage());
            }
        };
        mWebSocketClient.connect();
    }
}

通常情况下我可以实现它但是当我希望它放入单独的包中时如何使用回调?请任何人帮助我

1 个答案:

答案 0 :(得分:2)

你可以添加一些接口WebSocketListener, 它将包含onMessage,onClose,onError等。

并且在SocketCls的构造函数中,您可以设置此侦听器并在websockets回调中使用它

public class SocketCls {
public interface SocketListener  {
    void onOpen(ServerHandshake serverHandshake);
    void onMessage(String s);
    void onClose(int i, String s, boolean b);

}

SocketListener listener;

public SocketCls(SocketListener l) {
    listener = l;
}
private WebSocketClient mWebSocketClient;
private void connectWebSocket(String url) throws URISyntaxException {
    URI uri;
    uri = new URI(url);

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
            mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            listener.onOpen(serverHandshake);
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            // Here i want to use callback
            listener.onMessage(s);
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
            listener.onClose(i, s, b);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}

}