Android uses websocket protocol to communicate with the server

Source: Internet
Author: User

A recent project requires the server to actively push messages to the client. In this case, the HTTP connection is unavailable. The blogger asked a friend and recommended the websocket protocol to me. I tested it and found that the effect was good.

Android itself does not websocket library, need to download http://autobahn.ws/android/downloads

Client code ....

The interface layout is self-written, which is very simple with two buttons

Package COM. example. test; import COM. example. test. r; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. toast; import de. tavendo. autobahn. websocketconnection; import de. tavendo. autobahn. websocketconnectionhandler; import de. tavendo. autobahn. websocketexcept Ion; public class mainactivity extends activity implements onclicklistener {private button Bt; private edittext ed_name; private edittext ed_text; private button Bt1; websocketconnection WSC; @ overrideprotected void oncreate (bundle savedinstancestate. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); bt = (button) findviewbyid (R. id. BT); ed_name = (edittext) findviewbyid (R. id. ed_n AME); ed_text = (edittext) findviewbyid (R. id. ed_text); Bt1 = (button) findviewbyid (R. id. bt1); BT. setonclicklistener (this); bt1.setonclicklistener (this); WSC = new websocketconnection ();} private void connect () {system. out. println ("START websocket //"); try {WSC. connect ("WS: // 192.168.1.245: 8080/driveserver/mainservlet", new websocketconnectionhandler () {@ overridepublic void onbinarymessage (byte [] payload) {s Ystem. out. println ("onbinarymessage size =" + payload. length) ;}@ overridepublic void onclose (INT code, string reason) {system. out. println ("onclose reason =" + reason);} @ overridepublic void onopen () {system. out. println ("onopen"); showtext ("connection successful"); // WSC. sendtextmessage ("Hello! "); // WSC. disconnect () ;}@ overridepublic void onrawtextmessage (byte [] payload) {system. out. println ("onrawtextmessage size =" + payload. length) ;}@ overridepublic void ontextmessage (string payload) {system. out. println ("ontextmessage" + payload); showtext (payload) ;}});} catch (websocketexception e) {// todo auto-generated catch blocke. printstacktrace () ;}@ overridepublic void onclick (view v) {// todo auto-generated method stubint id = v. GETID (); Switch (ID) {case R. id. BT: WSC. sendtextmessage ("I Am a client, I send data to the server through ws"); break; case R. id. bt1: connect (); break; default: break;} private void showtext (string MSG) {toast. maketext (this, MSG, 0 ). show ();}}

The following is the server code:

Use the websocket library that comes with jetty7.

Package COM. websocket; import Java. io. ioexception; import Java. io. unsupportedencodingexception; import Java. NIO. bytebuffer; import Java. NIO. charbuffer; import Java. text. simpledateformat; import Java. util. arraylist; import Java. util. date; import Java. util. hashmap; import Java. util. list; import Java. util. map; import Java. util. set; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservletrequest; Import javax. servlet. HTTP. httpservletresponse; import Org. eclipse. jetty. websocket. websocket; import Org. eclipse. jetty. websocket. websocket. ontextmessage; import Org. eclipse. jetty. websocket. websocketservlet; public class chatwebsocketservlet extends websocketservlet {Private Static final long serialversionuid = 911879078000755859l; private list <mywebsocket> List = new arraylist <mywebsocket> (); Class mywe Bsocket implements ontextmessage {private string username = "anonymous user"; Public mywebsocket (string username) {If (username! = NULL & username. length ()> 0) {This. username = username ;}} private connection conn; Public void onclose (INT arg0, string arg1) {// todo auto-generated method stubsystem. out. println ("onopen disconnected ........ "+ Arg1 +" "+ arg0); list. remove (this);} public void onopen (connection arg0) {// todo auto-generated method stubsystem. out. println ("onopen connection ............ "+ Arg0.getmaxidletime (); this. Conn = arg0; If (! List. contains (arg0) {list. add (this);} else {system. out. println ("this user has connected");} system. out. println (".. "+ list. size ();} public void onmessage (string arg0) {string toname = arg0.substring (0, 3); system. out. println ("toname -->" + toname); try {list. get (0 ). getconn (). sendmessage (arg0.substring (3); system. out. println ("sent data" + arg0.substring (3);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} private connection getconn () {return this. conn ;}} public websocket dowebsocketconnect (httpservletrequest arg0, string arg1) {// todo auto-generated method stubstring name = ""; name = arg0.getparameter ("username"); system. out. println (name + "is connected"); return New mywebsocket (name) ;}@ overrideprotected void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// todo auto-generated method stubsuper. service (request, response );}}

Welcome to the discussion. For more information, see the source.

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.