ANDROID WebSocket+STOMP 1.0版本

JoeySheng發表於2016-07-20

Android WebSocket並沒有原生的支援,所以那些第三方庫如雨後春筍的出現了,那些就不舉例了,這裡就把一些最簡單的開源的東西整合到一起,並且加入了對STOMP的支援,這裡命名為cn.fullstacks.websocket,下載地址:http://download.csdn.net/detail/joeysheng/9581442

下面來看看怎麼使用

WebSocket

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
List<BasicNameValuePair> extraHeaders = Arrays.asList(
    newBasicNameValuePair("Cookie","session=abcd");
);
 
WebSocketClient client =newWebSocketClient(URI.create("wss://irccloud.com"),newWebSocketClient.Handler() {
    @Override
    publicvoidonConnect() {
        Log.d(TAG,"Connected!");
    }
 
    @Override
    publicvoidonMessage(String message) {
        Log.d(TAG, String.format("Got string message! %s", message));
    }
 
    @Override
    publicvoidonMessage(byte[] data) {
        Log.d(TAG, String.format("Got binary message! %s", toHexString(data));
    }
 
    @Override
    publicvoidonDisconnect(intcode, String reason) {
        Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
    }
 
    @Override
    publicvoidonError(Exception error) {
        Log.e(TAG,"Error!", error);
    }
}, extraHeaders);
 
client.connect();

連通之後就可以傳送訊息了

1
2
3
4
// Later…
client.send("hello!");
client.send(newbyte[] {0xDE,0xAD,0xBE,0xEF});
client.disconnect();

STOMP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Map<String,String> headersSetup =newHashMap<String,String>();
headersSetup.put("Cookie","session=abc");
Stomp stomp = new Stomp("ws://localhost:8080/wsport", headersSetup,newListenerWSNetwork() {
    @Override
    publicvoidonState(intstate) {
        Log.d("stomp onSate",String.format("state:%n",state));
    }
});
stomp.connect();
//訂閱主題
stomp.subscribe(newSubscription("topic/greetings",newListenerSubscription() {
    @Override
    publicvoidonMessage(Map<String, String> headers, String body) {
        //接收到訊息
    }
}));

連通好之後就可以傳送訊息了

1
2
stomp.send("/websocket/sendToTopic", headers,"hello stomp!");
stomp.disconnect();

相關文章