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( new BasicNameValuePair( "Cookie" , "session=abcd" ); ); WebSocketClient client = new WebSocketClient(URI.create( "wss://irccloud.com" ), new WebSocketClient.Handler()
{ @Override public void onConnect() { Log.d(TAG, "Connected!" ); } @Override public void onMessage(String message) { Log.d(TAG, String.format( "Got string message! %s" , message)); } @Override public void onMessage( byte []
data) { Log.d(TAG, String.format( "Got binary message! %s" , toHexString(data)); } @Override public void onDisconnect( int code,
String reason) { Log.d(TAG, String.format( "Disconnected! Code: %d Reason: %s" , code, reason)); } @Override public void onError(Exception error) { Log.e(TAG, "Error!" , error); } }, extraHeaders); client.connect(); |
連通之後就可以傳送訊息了
1
2
3
4
|
// Later…
client.send( "hello!" ); client.send( new byte [] { 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 = new HashMap<String,String>(); headersSetup.put( "Cookie" , "session=abc" ); @Override public void onState( int state)
{ Log.d( "stomp onSate" ,String.format( "state:%n" ,state)); } }); stomp.connect(); //訂閱主題 stomp.subscribe( new Subscription( "topic/greetings" , new ListenerSubscription()
{ @Override public void onMessage(Map<String, String> headers, String body) { //接收到訊息 } })); |
連通好之後就可以傳送訊息了
1
2
|
stomp.send( "/websocket/sendToTopic" , headers, "hello stomp!" ); stomp.disconnect(); |