tomcat websocket:借助tomcat容器运行websocket 服务端
jsp websocket:借助jsp,h5,js,sockjs实现websocket客户端
java-websocket:借助独立的组件实现websocket客户端
代码部分:
tomcat websocket实现
1 package com.ws; 2 3 import com.alibaba.fastjson.JSONObject; 4 import com.jfinal.kit.StrKit; 5 import com.util.dll.RsBean; 6 import com.util.dll.S50Util; 7 8 import javax.websocket.*; 9 import javax.websocket.server.PathParam; 10 import javax.websocket.server.ServerEndpoint; 11 import java.io.IOException; 12 import java.util.Map; 13 import java.util.concurrent.ConcurrentHashMap; 14 15 /** 16 * websocket 服务器 with tomcat9 17 * @ClassName: WebsocketServer 18 * @Description: TODO 19 * @author dhdu@qq.com 20 *d 21 */ 22 @ServerEndpoint("/ws/{sid}") 23 public class WebsocketServer { 24 private static int onlineCount = 0; 25 private static Map<String, WebsocketServer> clients = new ConcurrentHashMap<String, WebsocketServer>(); 26 private Session session; 27 private String sid; 28 29 @OnOpen 30 public void onOpen(@PathParam("sid") String sid, Session session) throws IOException { 31 32 this.sid = sid; 33 this.session = session; 34 addOnlineCount(); 35 clients.put(sid, this); 36 System.out.println("WebSocket 已连接 sid:"+sid); 37 38 } 39 40 @OnClose 41 public void onClose() throws IOException { 42 clients.remove(sid); 43 subOnlineCount(); 44 System.out.println("WebSocket 已关闭 sid:"+sid); 45 } 46 47 @OnMessage 48 public void onMessage(String message) throws IOException { 49 50 System.out.println("WebSocket Mess:"+message); 51 JSONObject jsonTo = JSONObject.parseObject(message); 52 //System.out.println(jsonTo.getString("to") +":"+ jsonTo.getString("msg")); 53 String rs_mess = ""; 54 RsBean rb=new RsBean(); 55 int t=jsonTo.getIntValue("t"); 56 //1aaa 2bbb 3ccc 57 switch(t) 58 { 59 case 1: 60 rs_mess=jsonTo.getString("msg"); 61 rb.setRs(rs_mess); 62 break; 63 case 2: 64 //rb=...; 65 break; 66 67 } 68 rb.setType(t); 69 String mess=JSONObject.toJSONString(rb); 70 //发送消息 71 if(jsonTo.containsKey("to")) 72 { 73 if (!jsonTo.getString("to").equalsIgnoreCase("all")) { 74 sendMessageTo(mess, jsonTo.getString("to")); 75 } else { 76 sendMessageAll(mess); 77 } 78 }else 79 sendMessageAll(mess); 80 } 81 82 @OnError 83 public void onError(Session session, Throwable error) { 84 error.printStackTrace(); 85 } 86 87 public void sendMessageTo(String message, String To) throws IOException { 88 // session.getBasicRemote().sendText(message); 89 //session.getAsyncRemote().sendText(message); 90 for (WebsocketServer item : clients.values()) 91 { 92 if (item.sid.equals(To) ) 93 item.session.getAsyncRemote().sendText(message); 94 } 95 } 96 97 public void sendMessageAll(String message) throws IOException { 98 for (WebsocketServer item : clients.values()) 99 { 100 item.session.getAsyncRemote().sendText(message); 101 } 102 } 103 104 105 106 public static synchronized int getOnlineCount() { 107 return onlineCount; 108 } 109 110 public static synchronized void addOnlineCount() { 111 WebsocketServer.onlineCount++; 112 } 113 114 public static synchronized void subOnlineCount() { 115 WebsocketServer.onlineCount--; 116 } 117 118 public static synchronized Map<String, WebsocketServer> getClients() { 119 return clients; 120 } 121 } 122 123 124 /** 125 * 126 */ 127 package com.util.dll; 128 129 import java.io.Serializable; 130 131 /** 132 * 结果bean 133 * @author dhdu@qq.com 134 */ 135 public class RsBean implements Serializable { 136 137 private int code;//状态码 1:yes 0:no 138 private String rs;//结果 139 private int type;//参数 140 public RsBean() { 141 code=1; 142 rs="成功"; 143 } 144 145 public String toStr() 146 { 147 return "code:"+code+",rs:"+rs; 148 } 149 public int getCode() { 150 return code; 151 } 152 public void setCode(int code) { 153 this.code = code; 154 } 155 public String getRs() { 156 return rs; 157 } 158 public void setRs(String rs) { 159 this.rs = rs; 160 } 161 public int getType() { 162 return type; 163 } 164 public void setType(int type) { 165 this.type = type; 166 } 167 168 }
jsp websocket实现
1 <script type="text/javascript" src="/js/sockjs/sockjs.min.js"></script> 2 3 4 <%@ page contentType="text/html;charset=UTF-8"%> 5 <script type="text/javascript"> 6 //${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${request.contextPath}/ 7 var ip='${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}'; 8 var websocket = null; 9 var sid='${pageContext.session.id}'; 10 var app_sid; 11 var app_msg; 12 if('WebSocket' in window) 13 { 14 websocket = new WebSocket("ws://"+ip+"/ws/"+sid); 15 } else if('MozWebSocket' in window) 16 { 17 websocket = new MozWebSocket("ws://"+ip+"/ws/"+sid); 18 } else 19 { 20 websocket = new SockJS(ip+"/ws/"+sid); 21 } 22 //连接发生错误的回调方法 23 websocket.onerror = function () { 24 setMessageInnerHTML("数据通讯发生错误"); 25 }; 26 //连接成功建立的回调方法 27 websocket.onopen = function () { 28 //连接成功 29 setMessageInnerHTML("###1"); 30 } 31 //接收到消息的回调方法 32 websocket.onmessage = function (event) { 33 // 34 setMessageInnerHTML(event.data,1); 35 } 36 //连接关闭的回调方法 37 websocket.onclose = function () { 38 setMessageInnerHTML("数据通讯关闭"); 39 } 40 //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 41 window.onbeforeunload = function () { 42 closeWebSocket(); 43 } 44 //将消息显示在网页上 45 function setMessageInnerHTML(innerHTML,p) { 46 if(p)//对象信息json 47 { 48 var mess=JSON.parse(innerHTML); 49 if(mess.code==1)//对象信息 正常 50 { 51 alert(mess.rs); 52 } 53 else //对象信息 异常 54 { 55 alert(mess.rs); 56 } 57 58 59 60 }else //非json信息 61 { 62 if("###1"==innerHTML) 63 { 64 alert("It's ready "); 65 } 66 67 } 68 } 69 //关闭WebSocket连接 70 function closeWebSocket() { 71 websocket.close(); 72 } 73 //发送消息 74 function sendWSMess(t) 75 { 76 // 77 var mobj={}; 78 mobj.to=sid;//"all"; 79 mobj.t=t;//1aaa 2bbb 3ccc 80 switch(t) 81 { 82 case 1: 83 var msg = $('#mess').val(); 84 mobj.msg=msg; 85 break; 86 case 2: 87 88 break; 89 case 3: 90 91 break; 92 93 default: 94 95 break; 96 } 97 98 websocket.send(JSON.stringify(mobj)); 99 } 100 101 102 </script>
java-websocket实现
1 package com.test; 2 3 import cn.hutool.core.codec.Base62; 4 import cn.hutool.core.util.CharsetUtil; 5 import com.alibaba.fastjson.JSONObject; 6 import org.java_websocket.client.WebSocketClient; 7 import org.java_websocket.drafts.Draft_6455; 8 import org.java_websocket.handshake.ServerHandshake; 9 10 import java.net.URI; 11 import java.util.HashMap; 12 import java.util.Map; 13 14 public class TestSocket { 15 16 17 public static void main(String[] args) 18 { 19 String base62="c2XSlpb4BOHK6E5T2FuzNllu"; 20 21 test(base62); 22 } 23 static void test(String base62) 24 { 25 //get socket msg 26 String content= Base62.decodeStr(base62, CharsetUtil.CHARSET_UTF_8); 27 System.out.println("[socket msg]"+content); 28 if(content.startsWith("ws://")) 29 { 30 String contents[]=content.split("/"); 31 String sids[]=contents[contents.length-1].split("_"); 32 Map rb = new HashMap<>(); 33 rb.put("t", 8); 34 rb.put("to", sids[0]); 35 rb.put("msg", "666666,"+sids[1]); 36 37 System.out.println("[msg body]"+JSONObject.toJSONString(rb)); 38 String uri = content.replaceFirst(sids[0]+"_",""); 39 //ws://192.6.6.1:80/xxx/ws/9694F2FE523B9A91F06519E7166C0CEB_85D04AA27EEC4D079DED5908FEB2117F 40 41 //create ws client 42 WebSocketClient wcc = new WebSocketClient(URI.create(uri), new Draft_6455()) { 43 44 @Override 45 public void onMessage(String message) { 46 String tttt = "(onMessage)got: " + message + "\n"; 47 System.out.println(tttt); 48 //{"rs":"ok","code":1,"type":9} 49 //第二步,得到消息,过滤 类型9的消息为登录结果 50 JSONObject jsonTo = JSONObject.parseObject(message); 51 if (jsonTo.getInteger("type").intValue() == 9) { 52 System.out.println(jsonTo); 53 System.out.println("APP 接收来自server的信息表示 登录成功"); 54 } 55 56 } 57 58 @Override 59 public void onOpen(ServerHandshake handshake) { 60 String tttt = "(onOpen)You are connected to ChatServer: " + getURI() + "\n"; 61 System.out.println(tttt); 62 //第一步,扫码解析之后,封装消息,发送(登录信息) 63 this.send(JSONObject.toJSONString(rb)); 64 } 65 66 @Override 67 public void onClose(int code, String reason, boolean remote) { 68 String tttt = "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n"; 69 System.out.println(tttt); 70 } 71 72 @Override 73 public void onError(Exception ex) { 74 75 ex.printStackTrace(); 76 77 } 78 }; 79 // open connect 80 wcc.connect(); 81 }else 82 { 83 System.out.println(content); 84 } 85 86 } 87 88 } 89