android websocket推送
1、通过WebSocketServlet来实现
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; import org.apache.catalina.websocket.WsOutbound; public class ChatWebSocketServlet extends WebSocketServlet { /** * */ private static final long serialVersionUID = 911879078000755859L; //private final Map<Integer, WsOutbound> map = new HashMap<Integer, WsOutbound>(); private final Map<String,WsOutbound> users = new HashMap<String,WsOutbound>(); @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { String username = null; try { username = request.getParameter("username"); System.out.println(username); if(username != null){ username = new String(username.getBytes("ISO8859_1"),"UTF-8"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(username+" 请求连接:"); return new ChatMessageInbound(username); } class ChatMessageInbound extends MessageInbound { private String userName = "user"; public ChatMessageInbound(String userName) { this.userName = userName; } @Override protected void onOpen(WsOutbound outbound) { users.put(userName, outbound); System.out.println(userName+"上线了,总共"+users.size()+"人在线"); super.onOpen(outbound); } @Override protected void onClose(int status) { users.remove(userName); System.out.println("下线:"+userName); super.onClose(status); } @Override protected void onBinaryMessage(ByteBuffer buffer) throws IOException { // TODO Auto-generated method stub } @Override protected void onTextMessage(CharBuffer buffer) throws IOException { String msg = buffer.toString(); System.out.println(userName+":"+msg); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); msg = userName+" " + sdf.format(date)+":\n" + msg; broadcast(msg); } private void broadcast(String msg) { Set<String> set = users.keySet(); for (String name : set) { WsOutbound outbound = users.get(name); CharBuffer buffer = CharBuffer.wrap(msg); try { outbound.writeTextMessage(buffer); outbound.flush(); } catch (Exception e) { e.printStackTrace(); } System.out.println(name+"----"); } } } }
2、通过@ServerEndpoint注解
import java.io.IOException; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/ws/chat/{nickName}") public class Chat { /** * 连接对象集合 */ private static final Set<Chat> connections = new CopyOnWriteArraySet<Chat>(); private String nickName; /** * WebSocket Session */ private Session session; public Chat() { } /** * 打开连接 * * @param session * @param nickName */ @OnOpen public void onOpen(Session session, @PathParam(value = "nickName") String nickName) { this.session = session; this.nickName = nickName; connections.add(this); String message = String.format("System> %s %s", this.nickName, " has joined."); Chat.broadCast(message); System.out.println(message); } /** * 关闭连接 */ @OnClose public void onClose() { connections.remove(this); String message = String.format("System> %s, %s", this.nickName, " has disconnection."); Chat.broadCast(message); System.out.println(message); } /** * 接收信息 * * @param message * @param nickName */ @OnMessage public void onMessage(String message, @PathParam(value = "nickName") String nickName) { Chat.broadCast(nickName + ">" + message); System.out.println(message); } /** * 错误信息响应 * * @param throwable */ @OnError public void onError(Throwable throwable) { System.out.println(throwable.getMessage()); } /** * 发送或广播信息 * * @param message */ private static void broadCast(String message) { for (Chat chat : connections) { try { synchronized (chat) { chat.session.getBasicRemote().sendText(message); } } catch (IOException e) { connections.remove(chat); try { chat.session.close(); } catch (IOException e1) { } Chat.broadCast(String.format("System> %s %s", chat.nickName, " has bean disconnection.")); System.out.println(String.format("System> %s %s", chat.nickName, " has bean disconnection.")); } } } }
3、android
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; 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 { final WebSocketConnection wsc = new WebSocketConnection(); private EditText edt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edt = (EditText) findViewById(R.id.edt1); findViewById(R.id.btn1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (wsc.isConnected()) { wsc.sendTextMessage(edt.getText().toString()); } else { Toast.makeText(getApplicationContext(), "请先加入", Toast.LENGTH_SHORT).show(); } } }); // System.out.println("websocket///"); findViewById(R.id.btn2).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { //"ws://192.168.1.106:9090/websocket01/chat.ws?username=server11" String url = "ws://192.168.1.106:8080/websocket01/ws/chat/server11"; wsc.connect(url, 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"); 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); edt.setText(payload); } }); } catch (WebSocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } @Override protected void onStop() { wsc.disconnect(); super.onStop(); } }
来自网络,稍加修改。
道法自然