1、StartFilter.java
package cn.xydata.pharmacy.websocket; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.java_websocket.WebSocketImpl; import cn.xydata.pharmacy.websocket.WSServer;; public class StartFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { } public void init(FilterConfig arg0) throws ServletException { this.startWebsocketInstantMsg(); } /** * 启动即时聊天服务 */ public void startWebsocketInstantMsg() { WebSocketImpl.DEBUG = false; WebServer s = new WebServer(6004); s.start(); } }
2、WebServer.java
package cn.xydata.pharmacy.websocket; import java.net.InetSocketAddress; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; public class WebServer extends WebSocketServer { public WebServer(int port) { super(new InetSocketAddress(port)); } public WebServer(InetSocketAddress address) { super(address); } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { // ws连接的时候触发的代码,onOpen中我们不做任何操作 System.out.println("onOpen"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { //断开连接时候触发代码 userLeave(conn); System.out.println(reason); System.out.println("onClose"); } @Override public void onMessage(WebSocket conn, String message) { System.out.println(message); System.out.println("onMessage"); if(null != message){ String userName = message.replaceFirst("online", message);//用户名 userJoin(conn,userName);//用户加入 } } @Override public void onError(WebSocket conn, Exception ex) { //错误时候触发的代码 System.out.println("on error"); ex.printStackTrace(); } /** * 去除掉失效的websocket链接 * @param conn */ private void userLeave(WebSocket conn){ WsPool.removeUser(conn); } /** * 将websocket加入用户池 * @param conn * @param userName */ private void userJoin(WebSocket conn,String userName){ WsPool.addUser(userName, conn); } // public void start() { // if( selectorthread != null ) // throw new IllegalStateException( getClass().getName() + " can only be started once." ); // new Thread( this ).start();; // } // public static void main(String args[]){ // WebSocketImpl.DEBUG = false; // int port = 8887; // 端口 // WsServer s = new WsServer(port); // s.start(); // } @Override public void onStart() { System.out.println("onstart"); } }
3、WsPool.java
package cn.xydata.pharmacy.websocket; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.java_websocket.WebSocket; public class WsPool { private static final Map<WebSocket, String> wsUserMap = new HashMap<WebSocket, String>(); /** * 通过websocket连接获取其对应的用户 * * @param conn * @return */ public static String getUserByWs(WebSocket conn) { return wsUserMap.get(conn); } /** * 根据userName获取WebSocket,这是一个list,此处取第一个 * 因为有可能多个websocket对应一个userName(但一般是只有一个,因为在close方法中,我们将失效的websocket连接去除了) * * @param user */ public static WebSocket getWsByUser(String userName) { Set<WebSocket> keySet = wsUserMap.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String cuser = wsUserMap.get(conn); if (cuser.equals(userName)) { return conn; } } } return null; } /** * 向连接池中添加连接 * * @param inbound */ public static void addUser(String userName, WebSocket conn) { wsUserMap.put(conn, userName); // 添加连接 } /** * 获取所有连接池中的用户,因为set是不允许重复的,所以可以得到无重复的user数组 * * @return */ public static Collection<String> getOnlineUser() { List<String> setUsers = new ArrayList<String>(); Collection<String> setUser = wsUserMap.values(); for (String u : setUser) { setUsers.add(u); } return setUsers; } /** * 移除连接池中的连接 * * @param inbound */ public static boolean removeUser(WebSocket conn) { if (wsUserMap.containsKey(conn)) { wsUserMap.remove(conn); // 移除连接 return true; } else { return false; } } /** * 向特定的用户发送数据 * * @param user * @param message */ public static void sendMessageToUser(WebSocket conn, String message) { if (null != conn && null != wsUserMap.get(conn)) { conn.send(message); } } /** * 向所有的用户发送消息 * * @param message */ public static void sendMessageToAll(String message) { Set<WebSocket> keySet = wsUserMap.keySet(); synchronized (keySet) { for (WebSocket conn : keySet) { String user = wsUserMap.get(conn); if (user != null) { conn.send(message); } } } } }
4、WSServer.java
package cn.xydata.pharmacy.websocket; import java.io.UnsupportedEncodingException; import java.util.Collection; import org.java_websocket.WebSocket; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; //@ServerEndpoint注解中的内容是用户客户端websocket的连接url,例如ws://127.0.0.1:80/websocket/ws, //结构形式为“ws://ip:端口/项目名/指定的url” @Controller @RequestMapping(value="WSServer") public class WSServer { // @SystemControllerLog(description="添加用户信息") // @RequestMapping(value="addParticipant",method = RequestMethod.POST) // @ResponseBody() // public Object addParticipant(HttpServletRequest request, // HttpServletResponse response) { // Map<String,Object> result = new HashMap<String,Object>(); // // result.put("success", "500"); // return result; // } @ResponseBody @RequestMapping("sendWs") public String sendWs(String message) throws Exception { message = new String(message.getBytes("ISO-8859-1"),"UTF-8"); WsPool.sendMessageToAll(message); return message; } @ResponseBody @RequestMapping("sendWsOne") public String sendWsOne() { Collection<String> conns = WsPool.getOnlineUser(); System.out.println(conns + "sendWsOne"); return "123"; } }
另需两个jar包:
javax.websocket-api-1.1.jar
Java-WebSocket-1.3.7.jar
在web.xml中配置过滤器如下:
<filter> <filter-name>startFilter</filter-name> <filter-class>StartFilter.java路径</filter-class> </filter>
怎么引用?一段代码即可:
WsPool.sendMessageToAll(p.getRealName()+","+p.getPosition()+","+mp.getSeatNo());
客户端怎么弄?
var ws = new WebSocket("ws://180.76.236.11:6005"); //握手协议,服务器ip地址以及服务器提供给WebSocket进程端口,与StartFilter.java中startWebsocketInstantMsg方法内的端口保持一致 ws.onopen = function(){ ws.send("online-hello"); console.log("连接...") } //处理服务器发送来的数据 ws.onmessage = function(e){ var text = e.data; var arr = text.split(','); sign(arr[0],arr[1],arr[2]); //sign函数的作用是将从服务器发送来的参会人员信息显示在欢迎屏 } ws.onclose = function(){ console.log("连接关闭"); } ws.onerror = function(){ console.log('连接失败'); }