欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

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

时间:2020-10-07 14:28:38|栏目:Android代码|点击:

最近做一个项目,需求中需要服务器主动推送消息到客户端。这样的话一般的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编程处理窗口控件大小,形状,像素等UI元素工具类

栏    目:Android代码

下一篇:Android ContentProvider的实现及简单实例代码

本文标题:android利用websocket协议与服务器通信

本文地址:http://www.codeinn.net/misctech/8191.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有