【问题标题】:Connect android app to sockjs server将 android 应用程序连接到 sockjs 服务器
【发布时间】:2015-10-17 03:59:17
【问题描述】:

我正在开发一个原生安卓应用, 我必须将我的应用程序连接到 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 poll error'

【问题讨论】:

    标签: android sockets sockjs


    【解决方案1】:

    现在使用以下技巧成功连接到 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 写了一个客户端:github.com/vishal-raj/SockJsClientAndroid
    • 有没有办法在 android 中使用 sockjs 客户端向服务器发送消息?
    • 实现 sock.send('') 函数。
    • 我是否必须在 Temple.html 中使用 sock.send() 创建一个参数化函数并从 Android 调用该函数?
    【解决方案2】:

    我建议你使用socket.io。

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

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2020-12-01
      • 2017-07-23
      相关资源
      最近更新 更多