关于套接字:将android应用连接到sockjs服务器

Connect android app to sockjs server

我正在使用本机android应用程序,
我必须将我的应用程序连接到Sockjs服务器。
我尝试与Socket.IO,高速公路,WebSockets连接,但未连接。
是否有适用于Android的sockjs客户端?
请帮助,谢谢。

Socket.IO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 \\'


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

1
2
3
4
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接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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");
        };
    }

调用js函数:

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


我建议您使用socket.io

Socket.io Blog

上有一个很好的客户端和服务器示例