android利用WebSocket实现消息推送

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

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

(2)、web.xml的配置

 

 <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)、服务端代码

 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)、客户端代码

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
            
        }
        
    }
}

 

posted on 2015-06-04 22:27  liu_zl  阅读(11467)  评论(2编辑  收藏  举报