连接安卓应用到SockJS服务器

4

我正在开发一款原生安卓应用程序, 我需要将我的应用程序连接到Sockjs服务器。 我尝试了使用Socket.IO、Autobahn、WebSockets进行连接,但都无法连接成功。 是否有适用于安卓的Sockjs客户端? 请帮忙,谢谢。

Socket.IO:

private void connectToSocket(String serverUrl, String accessKey) {
    IO.Options opts = new IO.Options();
    opts.forceNew = true;
    opts.reconnection = true;
    //opts.query = "accessKey="+accessKey;
    String host = serverUrl;

    try {
        mSocket = IO.socket(host, opts);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT, onConnect);
    mSocket.on("new message", onNewMessage);
    mSocket.connect().emit("accessKey", accessKey);
    if (mSocket.connected()) {
        Log.d("SocketMsg: ", "Connected");
    }

}

private Emitter.Listener onConnect = new Emitter.Listener() {

    @Override
    public void call(final Object... args) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("SocketMsg: ", args[0].toString());
                //mSocket.emit("accessKey", accessKey);
                Toast.makeText(MainActivity.this.getApplicationContext(),
                        "Connect", Toast.LENGTH_LONG).show();
                for (Object o : args) {
                    Log.i("IO " + Socket.EVENT_CONNECT_ERROR, o.toString());
                }
            }
        });
    }
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("SocketMsg: ", args[0].toString());
                Toast.makeText(MainActivity.this.getApplicationContext(),
                        "Error", Toast.LENGTH_LONG).show();
                for (Object o : args) {
                    Log.i("IO " + Socket.EVENT_CONNECT_ERROR, o.toString());
                }
            }
        });
    }
};

它正在出现“xhr轮询错误”。
2个回答

7

现在,使用以下技巧成功连接到SockJS:

1. Place a web view and set its visibility to gone.
2. Use SockJS client in webview.
3. Create a javascript Interface that send data back to native code when get data from socket.
4. We have to call the function only once from native code.

JavaScript接口:

public class WebAppInterface {
    Context mContext;

    /**
     * Instantiate the interface and set the context
     */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /**
     * Show a toast from the web page
     */
    @JavascriptInterface
    public void msg(final String toast) {
        Log.d("msg: ", toast);
        if (toast.contains("{"))
            createMarkerList(toast);
    }
}

在Webview上使用SockJS客户端:
<script type="text/javascript">
    function connectToSocket(url, accessKey){
        Android.msg(String("called"));
        var sock = new SockJS("http://api.example.in:8182/realtime");
        sock.onopen = function() {
            Android.msg("open");
            sock.send(JSON.stringify({
              key: accessKey
            }));
        };

        sock.onclose = function() {
            Android.msg("close");
        };

        sock.onmessage = function(e) {
            result = e.data.replace(/,\s*$/, '');
            Android.msg(String(result));
        };

        sock.onerror = function(e) {
            Android.msg("error");
        };
    }
</script>

调用JS函数:

webView.loadUrl(javascript:connectToSocket(url, accessKey));

我也编写了一个SockJs客户端: https://github.com/vishal-raj/SockJsClientAndroid - Vishal Raj
您是否有在Android上使用sockjs客户端向服务器发送消息的方法? - kinjal patel
实现 sock.send('') 函数。 - Vishal Raj
1
我需要在temple.html中创建一个带有sock.send()参数的函数,并从Android调用该函数吗? - kinjal patel

0

我建议您使用socket.io

Socket.io博客上有一个很好的客户端和服务器示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接