赞
踩
websocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器的全双工通讯-允许服务器主动发起信息个客户端,
websocket’是一种持久协议,http是非持久协议。在websocket出现之前,是通过通过ajax轮询来实现网站实时推送消息给浏览器客户端。轮询是指由浏览器每隔一段时间向服务器发出 HTTP 请求,然后服务器返回最新的数据给客户端。轮询的效率低,非常浪费资源。
HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理,HTTP 协议无法实现服务器主动向客户端发起消息。
WebSocket 只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。
首先需要引入websocket的jar包,包括 tomcat-websocket.jar和websocket-api.jar,这两个jar包在tomcat7以上版本的lib目录下,将这两个jar包拷贝到项目的lib目录下。
编写websocketServer类
@ServerEndpoint(value = "/websocket/{oid}") public class WebsocketDemoServer { private Session session; private String oid; /** * * 连接建立后触发的方法 */ @OnOpen public void onOpen(@PathParam("oid") String oid, Session session) { this.session = session; this.oid = oid; System.out.println("onOpen=====" + oid); WebSocketMapUtil.put(oid, session); } /** * * 连接关闭后触发的方法 */ @OnClose public void onClose() { //从map中删除 WebSocketMapUtil.remove(this.oid); System.out.println("====== onClose:" + this.oid + " ======"); } /** * * 接收到客户端消息时触发的方法 */ @OnMessage public void onMessage(String params, Session session) throws Exception { System.out.println("收到来自" + this.oid + "的消息" + params); String result = "收到来自" + this.oid + "的消息" + params; //返回消息给Web Socket客户端(浏览器) session.getBasicRemote().sendText(result); } /** * * 发生错误时触发的方法 */ @OnError public void onError(Session session, Throwable error) { System.out.println(session.getId() + "连接发生错误" + error.getMessage()); error.printStackTrace(); } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } }
@ServerEndpoint注解表示websocket请求url,{oid}用来标识每一个websocket客户端的唯一id。
WebSocketMapUtil类 用来保存websocket客户端和websocket连接的对应关系
public class WebSocketMapUtil { public static ConcurrentMap<String, Session> webSocketMap = new ConcurrentHashMap<>(); public static void put(String key, Session session) { webSocketMap.put(key, session); } public static Session get(String key) { return webSocketMap.get(key); } public static void remove(String key) { webSocketMap.remove(key); } public static Collection<Session> getValues() { return webSocketMap.values(); } }
编写websocket客户端MyWebSocketClient类,需要java-websocket-1.5.2jar包
public class MyWebSocketClient extends WebSocketClient { public MyWebSocketClient(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake arg0) { // TODO Auto-generated method stub System.out.println("------ MyWebSocket onOpen ------"); } @Override public void onClose(int arg0, String arg1, boolean arg2) { // TODO Auto-generated method stub System.out.println("------ MyWebSocket onClose ------"); } @Override public void onError(Exception arg0) { // TODO Auto-generated method stub System.out.println("------ MyWebSocket onError ------"); } @Override public void onMessage(String arg0) { // TODO Auto-generated method stub System.out.println("-------- 接收到服务端数据: " + arg0 + "--------"); } }
编写websocket客户端测试类
public class WebSocketTest { public static void main(String[] args) { try { // 创建WebSocket客户端 MyWebSocketClient myClient = new MyWebSocketClient(new URI("ws://127.0.0.1:9091/web/websocket/345")); // 与服务端建立连接 myClient.connect(); while (!myClient.getReadyState().equals(ReadyState.OPEN)) { System.out.println("连接中。。。"); Thread.sleep(1000); } // 往websocket服务端发送数据 myClient.send("发送来自websocketClient 345的消息"); Thread.sleep(1000); // 关闭与服务端的连接 // myClient.close(); }catch (Exception e){ e.printStackTrace(); } // write your code here } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。