android利用websocket协议与服务器通信
最近做一个项目,需求中需要服务器主动推送消息到客户端。这样的话一般的http连接就不能使用了。博主问了个朋友,向我推荐websocket协议,特此测试了一下,发现效果很好。
android本身没有websocket的库,需要自己下载,下载地址。
客户端代码:
界面布局自己写,很简单的两个button
packagecom.example.test; importcom.example.test.R; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.Toast; importde.tavendo.autobahn.WebSocketConnection; importde.tavendo.autobahn.WebSocketConnectionHandler; importde.tavendo.autobahn.WebSocketException; publicclassMainActivityextendsActivityimplementsOnClickListener{ privateButtonbt; privateEditTexted_name; privateEditTexted_text; privateButtonbt1; WebSocketConnectionwsc; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt=(Button)findViewById(R.id.bt); ed_name=(EditText)findViewById(R.id.ed_name); ed_text=(EditText)findViewById(R.id.ed_text); bt1=(Button)findViewById(R.id.bt1); bt.setOnClickListener(this); bt1.setOnClickListener(this); wsc=newWebSocketConnection(); } privatevoidconnect(){ System.out.println("开始连接websocket///"); try{ wsc.connect("ws://192.168.1.245:8080/DriveServer/mainservlet", newWebSocketConnectionHandler(){ @Override publicvoidonBinaryMessage(byte[]payload){ System.out.println("onBinaryMessagesize=" +payload.length); } @Override publicvoidonClose(intcode,Stringreason){ System.out.println("onClosereason="+reason); } @Override publicvoidonOpen(){ System.out.println("onOpen"); showtext("连接成功"); //wsc.sendTextMessage("Hello!"); //wsc.disconnect(); } @Override publicvoidonRawTextMessage(byte[]payload){ System.out.println("onRawTextMessagesize=" +payload.length); } @Override publicvoidonTextMessage(Stringpayload){ System.out.println("onTextMessage"+payload); showtext(payload); } }); }catch(WebSocketExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub intid=v.getId(); switch(id){ caseR.id.bt: wsc.sendTextMessage("我是客户端,我通过ws往服务器发数据"); break; caseR.id.bt1: connect(); break; default: break; } } privatevoidshowtext(Stringmsg){ Toast.makeText(this,msg,0).show(); } }
下面是服务器代码:
用的是jetty7自带的websocket库
packagecom.websocket; importjava.io.IOException; importjava.io.UnsupportedEncodingException; importjava.nio.ByteBuffer; importjava.nio.CharBuffer; importjava.text.SimpleDateFormat; importjava.util.ArrayList; importjava.util.Date; importjava.util.HashMap; importjava.util.List; importjava.util.Map; importjava.util.Set; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.eclipse.jetty.websocket.WebSocket; importorg.eclipse.jetty.websocket.WebSocket.OnTextMessage; importorg.eclipse.jetty.websocket.WebSocketServlet; publicclassChatWebSocketServletextendsWebSocketServlet{ privatestaticfinallongserialVersionUID=911879078000755859L; privateListlist=newArrayList (); classMyWebSocketimplementsOnTextMessage{ privateStringuserName="匿名用户"; publicMyWebSocket(StringuserName){ if(userName!=null&&userName.length()>0){ this.userName=userName; } } privateConnectionconn; publicvoidonClose(intarg0,Stringarg1){ //TODOAuto-generatedmethodstub System.out.println("onOpen断开连接了。。。。。。。。"+arg1+""+arg0); list.remove(this); } publicvoidonOpen(Connectionarg0){ //TODOAuto-generatedmethodstub System.out .println("onOpen连接了。。。。。。。。。。。。"+arg0.getMaxIdleTime()); this.conn=arg0; if(!list.contains(arg0)){ list.add(this); }else{ System.out.println("这个用户已经连接了"); } System.out.println(".."+list.size()); } publicvoidonMessage(Stringarg0){ Stringtoname=arg0.substring(0,3); System.out.println("toname-->"+toname); try{ list.get(0).getConn() .sendMessage(arg0.substring(3)); System.out.println("发送的数据"+arg0.substring(3)); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } privateConnectiongetConn(){ returnthis.conn; } } publicWebSocketdoWebSocketConnect(HttpServletRequestarg0,Stringarg1){ //TODOAuto-generatedmethodstub Stringname=""; name=arg0.getParameter("username"); System.out.println(name+"isconnected"); returnnewMyWebSocket(name); } @Override protectedvoidservice(HttpServletRequestrequest, HttpServletResponseresponse)throwsServletException,IOException{ //TODOAuto-generatedmethodstub super.service(request,response); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。