onLoad() { var webSocket = new WebSocket("ws://localhost/ws/dd"); webSocket.onopen = function(event){ console.log("打开链接"); //console.log(event); //self.webSocketRes.string = event.type } ////接受服务器发送的消息 webSocket.onmessage = function(event){ console.log("接受服务器发送的消息 :"+event); console.log(event); //self.webSocketRes.string = self.webSocketRes.string + "--" + event.type //webSocket.close(); //webSocket = null; } webSocket.onerror = function(event){ console.log("webSocket.onerror:"); console.log(event.data); //self.webSocketRes.string = self.webSocketRes.string + "--" + event.type } webSocket.onclose = function(event){ console.log("webSocket.onclose:"); console.log(event); //self.webSocketRes.string = self.webSocketRes.string + "--" + event.type } setTimeout(function () { if (webSocket.readyState === WebSocket.OPEN) { webSocket.send("Hello WebSocket, I'm a text message."); } else { console.log("WebSocket instance wasn't ready..."); } }, 1000); },
package com.java456.socket; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; import com.java456.dao.UserDao; import com.java456.entity.User; import com.java456.service.UserService; import net.sf.json.JSONObject; import javax.annotation.Resource; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @ServerEndpoint("/ws/{username}") @Component public class WsServerEndpoint { private static final ConcurrentMap<String, WsServerEndpoint> USER_CLIENT_MAP = new ConcurrentHashMap<>(); private Session session; private String username = ""; private static int onlineCount = 0;// 记录在线人 @Resource private UserService userService; /** * #连接成功 * * @param session */ @OnOpen public void onOpen(Session session, @PathParam("username") String username) { System.out.println("连接成功,sessionid:" + session.getId() + ",username:" + username); this.session = session; this.username = username; if (USER_CLIENT_MAP.containsKey(username)) { USER_CLIENT_MAP.remove(username); USER_CLIENT_MAP.put(username, this); } else { USER_CLIENT_MAP.put(username, this); addOnlineCount(); } } /** * #连接关闭 * * @param session */ @OnClose public void onClose(Session session) { System.out.println("连接关闭:" + username); System.out.println("sessionid:" + session.getId()); if (USER_CLIENT_MAP.containsKey(username)) { USER_CLIENT_MAP.remove(username); // 从set中删除 subOnlineCount(); } } /** * #接受到客户端发送的消息 * * @param text */ @OnMessage public void onMsg(String msg, Session session) throws IOException { System.out.println("接受客户消息 "); System.out.println("消息内容: " + msg); System.out.println("sessionid: " + session.getId()); // String key = this.session.getId(); // USER_CLIENT_MAP.get(key).sendMessage(msg); // 解析发送的报文 // JSONObject jsonObject = JSONObject.fromObject(msg) ; // 追加发送人(防止串改) // jsonObject.put("username", this.username); // this.sendToAll(this.username + ":" + msg); // 这个返回的消息,是单独发给我的人发的。 可以在方法上面写返回 string // return "servet 发送:" + msg; } // 群发消息给所有客户 public void sendToAll(String msg) { USER_CLIENT_MAP.values().forEach(item -> { item.sendMessage(msg); }); } /** * #推送消息给客户端 * * @param message 消息内容 */ private void sendMessage(String message) { try { // 使用同步块和同步方法发送。看是否能防止产生IllegalStateException异常 // modify by caoshuo at 200506 synchronized (session) { session.getBasicRemote().sendText(message); } } catch (Exception e) { // 如果接受的人关闭了。这个会报错。 System.out.println( "websocket连接发送客户端发送消息时异常! 消息内容:" + message + ",sessionid:" + this.toString() + "____" + e); } } /** * 发生异常时的处理 * * @param session 客户端session * @param throwable session */ @OnError public void onError(Session session, Throwable throwable) { if (this.session != null && this.session.isOpen()) { System.out.println("websocket连接onError。inputSession:{}-localSession:{}" + session.getId() + this.toString() + throwable); } else { System.out.println("已经关闭的websocket连接发生异常!inputSession:{}-localSession:{}" + session.getId() + this.toString() + throwable); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WsServerEndpoint.onlineCount++; } public static synchronized void subOnlineCount() { WsServerEndpoint.onlineCount--; } }
<!--原生websocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!--原生websocket-->
站长微信:xiaomao0055
站长QQ:14496453