android利用WebSocket实现消息推送

1、webSocket服务端的配置与代码:

(1)、服务器端工程目录结构:

(2)、web.xml的配置

1
2
3
4
5
6
7
<servlet-name>webSocketServlet</servlet-name>
        <servlet- class >com.cn.controller.WebSocketServletService</servlet- class >
      </servlet>
    <servlet-mapping>
        <servlet-name>webSocketServlet</servlet-name>
        <url-pattern>/webSocketServlet</url-pattern>
    </servlet-mapping>

 

(3)、服务端代码

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
public  class  WebSocketServletService  extends  WebSocketServlet{
 
     private  static  final  long  serialVersionUID = 1L;
     private  static  List<MyMessageInbound> myMessageInbounds =  new  ArrayList<WebSocketServletService.MyMessageInbound>();
     @SuppressWarnings ( "deprecation" )
     @Override
     protected  StreamInbound createWebSocketInbound(String arg0,
             HttpServletRequest arg1) {
         // TODO Auto-generated method stub
         return  new  MyMessageInbound();
     }
     private  class  MyMessageInbound  extends  MessageInbound {
         WsOutbound myoutbound;
 
         /**
          * 打开连接
          */
         @Override
         public  void  onOpen(WsOutbound outbound) {
             try  {
                 System.out.println( "Open Client." );
                 this .myoutbound = outbound;
                 myMessageInbounds.add( this );
                 outbound.writeTextMessage(CharBuffer.wrap( "Hello!" ));
             catch  (IOException e) {
                 e.printStackTrace();
             }
         }
         @Override
         public  void  onClose( int  status) {
             System.out.println( "Close Clients." );
             myMessageInbounds.remove( this );
         }
 
         /**
          * 接收消息
          */
         @Override
         public  void  onTextMessage(CharBuffer cb)  throws  IOException {
             System.out.println( "Accept Message : "  + cb);
             for  (MyMessageInbound myMessageInbound : myMessageInbounds) {
                 CharBuffer buffer = CharBuffer.wrap(cb);
                 myMessageInbound.myoutbound.writeTextMessage(buffer);
                 myMessageInbound.myoutbound.flush();
             }
         }
         @Override
         public  void  onBinaryMessage(ByteBuffer bb)  throws  IOException {
         }
     }
}

2、android客户端配置与代码

(1)、导入java-websocket-1.3.0.jar

(2)、客户端代码

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public  class  MainActivity  extends  Activity {
     @Override
     protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
     }
     Handler handler= new  Handler()
     {
 
         @Override
         public  void  handleMessage(Message msg) {
             // TODO Auto-generated method stub
             Toast.makeText(MainActivity. this , msg.getData().getString( "info" ),Toast.LENGTH_SHORT).show();
         }
         
     };
     @Override
     public  boolean  onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.main, menu);
         return  true ;
     }
 
     @Override
     public  boolean  onOptionsItemSelected(MenuItem item) {
         // Handle action bar item clicks here. The action bar will
         // automatically handle clicks on the Home/Up button, so long
         // as you specify a parent activity in AndroidManifest.xml.
         int  id = item.getItemId();
         if  (id == R.id.action_settings) {
             URI uri= null ;
             try  {
                 uri =  new  URI( "ws://localhost/Breed/webSocketServlet" );
             catch  (URISyntaxException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             WebSocketWorker webSocketWorker= new  WebSocketWorker(uri,  new  Draft_17());
             try  {
                 webSocketWorker.connectBlocking(); //此处如果用webSocketWorker.connect();会出错,需要多注意
             catch  (InterruptedException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             webSocketWorker.send( "text" );
             return  true ;
         }
         return  super .onOptionsItemSelected(item);
     }
     
     private  class  WebSocketWorker  extends  WebSocketClient{
 
         public  WebSocketWorker(URI serverUri, Draft draft) {
             super (serverUri, draft);
         }
 
         @Override
         public  void  onClose( int  arg0, String arg1,  boolean  arg2) {
             // TODO Auto-generated method stub
             
         }
         @Override
         public  void  onError(Exception arg0) {
             // TODO Auto-generated method stub
             
         }
 
         @Override
         public  void  onMessage(String arg0) {
             // TODO Auto-generated method stub
             Bundle bundle= new  Bundle();
             bundle.putString( "info" ,arg0);
             Message message= new  Message();
             message.setData(bundle);
             handler.sendMessage(message);
         }

         @Override
         public  void  onOpen(ServerHandshake arg0) {
             // TODO Auto-generated method stub
             
         }
         
     }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值