Android uses WebSocket to Implement Message push and androidwebsocket

Source: Internet
Author: User

Android uses WebSocket to Implement Message push and androidwebsocket

1. Configuration and code of the webSocket Server:

(1) directory structure of the server project:

(2) web. xml configuration

<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) server code

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;

/**
* Open the connection.
*/
@ 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 );
}

/**
* Receive messages
*/
@ 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 client configuration and code

(1), import java-websocket-1.3.0.jar

(2) client code

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 (); // If webSocketWorker. connect () is used here, an error occurs. Pay attention to this.
} 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

}

}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.