Android开发

android利用websocket协议与服务器通信

本文主要是介绍android利用websocket协议与服务器通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最近做一个项目,需求中需要服务器主动推送消息到客户端。这样的话一般的http连接就不能使用了。博主问了个朋友,向我推荐websocket协议,特此测试了一下,发现效果很好。

android本身没有websocket的库,需要自己下载 ,下载地址

客户端代码:

界面布局自己写,很简单的两个button

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.WebSocketException; 
 
public class MainActivity extends Activity implements OnClickListener { 
 
 private Button bt; 
 private EditText ed_name; 
 private EditText ed_text; 
 private Button bt1; 
 WebSocketConnection wsc; 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  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 = new WebSocketConnection(); 
 
 } 
 
 private void connect() { 
  System.out.println("开始连接websocket///"); 
 
  try { 
 
   wsc.connect("ws://192.168.1.245:8080/DriveServer/mainservlet", 
     new WebSocketConnectionHandler() { 
     
      @Override 
      public void onBinaryMessage(byte[] payload) { 
       System.out.println("onBinaryMessage size=" 
         + payload.length); 
      } 
 
      @Override 
      public void onClose(int code, String reason) { 
       System.out.println("onClose reason=" + reason); 
      } 
 
      @Override 
      public void onOpen() { 
       System.out.println("onOpen"); 
       showtext("连接成功"); 
       // wsc.sendTextMessage("Hello!"); 
       // wsc.disconnect(); 
      } 
      @Override 
      public void onRawTextMessage(byte[] payload) { 
       System.out.println("onRawTextMessage size=" 
         + payload.length); 
      } 
 
      @Override 
      public void onTextMessage(String payload) { 
       System.out.println("onTextMessage" + payload); 
       showtext(payload); 
      } 
 
     }); 
  } catch (WebSocketException e) { 
   // TODO Auto-generated catch block 
   e.printStackTrace(); 
  } 
 
 } 
 @Override 
 public void onClick(View v) { 
  // TODO Auto-generated method stub 
  int id = v.getId(); 
  switch (id) { 
   case R.id.bt : 
    wsc.sendTextMessage("我是客户端,我通过ws往服务器发数据"); 
    break; 
   case R.id.bt1 : 
    connect(); 
    break; 
   default : 
    break; 
  } 
 } 
 private void showtext(String msg) { 
  Toast.makeText(this, msg, 0).show(); 
 } 
} 

下面是服务器代码:

用的是jetty7自带的websocket库

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 MyWebSocket implements OnTextMessage { 
  private String userName = "匿名用户"; 
 
  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 stub 
   System.out.println("onOpen 断开连接了。。。。。。。。" + arg1 + " " + arg0); 
   list.remove(this); 
  } 
 
  public void onOpen(Connection arg0) { 
   // TODO Auto-generated method stub 
   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()); 
  } 
 
  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("发送的数据" + arg0.substring(3)); 
   } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
   } 
  } 
 
  private Connection getConn() { 
   return this.conn; 
  } 
 } 
 
 public WebSocket doWebSocketConnect(HttpServletRequest arg0, String arg1) { 
  // TODO Auto-generated method stub 
  String name = ""; 
  name = arg0.getParameter("username"); 
  System.out.println(name + "is connected"); 
  return new MyWebSocket(name); 
 } 
 
 @Override 
 protected void service(HttpServletRequest request, 
   HttpServletResponse response) throws ServletException, IOException { 
  // TODO Auto-generated method stub 
  super.service(request, response); 
 } 
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。

这篇关于android利用websocket协议与服务器通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!