WebSocket实现聊天室业务的具体代码,供大家参考,具体内容如下
页面效果图
pom.xml
主要是spring-boot-starter-websocket包,websocket连接、发送信息。
org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-websocketorg.springframework.boot spring-boot-starter-thymeleaforg.webjars webjars-locator-coreorg.webjars.npm mdui0.4.0 org.webjars jquery3.3.1 org.springframework.boot spring-boot-devtoolsruntime com.alibaba fastjson1.2.49 org.springframework.boot spring-boot-starter-testtest
前台
html + js
websocket 前台主要包括四种方法:
- 打开连接:onopen
- 服务端发来消息:1.广播消息 2.更新在线人数 : onmessage
- 关闭连接 :onclose
- 通信失败 :onerror
WebSocket简单聊天室 menu 简单聊天室 search exit_to_app more_vert 欢迎: textsms 聊天内容 face 在线人数 0
后台
WebSocketChatApplication - 启动类
@SpringBootApplication
@RestController
public class WebSocketChatApplication {
@GetMapping("/")
public ModelAndView login() {
return new ModelAndView("/login");
}
@GetMapping("/index")
public ModelAndView index(String username, String password, HttpServletRequest request) throws UnknownHostException {
if (StringUtils.isEmpty(username)) {
username = "匿名用户";
}
ModelAndView mav = new ModelAndView("/chat");
mav.addObject("username", username);
mav.addObject("webSocketUrl", "ws://"+InetAddress.getLocalHost().getHostAddress()+":"+request.getServerPort()+request.getContextPath()+"/chat");
return mav;
}
public static void main(String[] args) {
SpringApplication.run(WebSocketChatApplication.class, args);
}
}
WebSocketConfig - WebSocket配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
Message - 封装信息类
public class Message {
public static final String ENTER = "ENTER";
public static final String SPEAK = "SPEAK";
public static final String QUIT = "QUIT";
private String type;//消息类型
private String username; //发送人
private String msg; //发送消息
private int onlineCount; //在线用户数
public static String jsonStr(String type, String username, String msg, int onlineTotal) {
return JSON.toJSonString(new Message(type, username, msg, onlineTotal));
}
public Message(String type, String username, String msg, int onlineCount) {
this.type = type;
this.username = username;
this.msg = msg;
this.onlineCount = onlineCount;
}
public static String getENTER() {
return ENTER;
}
public static String getSPEAK() {
return SPEAK;
}
public static String getQUIT() {
return QUIT;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getonlineCount() {
return onlineCount;
}
public void setonlineCount(int onlineCount) {
this.onlineCount = onlineCount;
}
}
WebSocketChatServer - 聊天服务端
前台对应的四种传输,后台进行处理操作
@Component
@ServerEndpoint("/chat")
public class WebSocketChatServer {
private static Map onlineSessions = new ConcurrentHashMap<>();
@onOpen
public void onOpen(Session session) {
onlineSessions.put(session.getId(), session);
sendMessageToAll(Message.jsonStr(Message.ENTER, "", "", onlineSessions.size()));
}
@onMessage
public void onMessage(Session session, String jsonStr) {
Message message = JSON.parseObject(jsonStr, Message.class);
sendMessageToAll(Message.jsonStr(Message.SPEAK, message.getUsername(), message.getMsg(), onlineSessions.size()));
}
@onClose
public void onClose(Session session) {
onlineSessions.remove(session.getId());
sendMessageToAll(Message.jsonStr(Message.QUIT, "", "", onlineSessions.size()));
}
@onError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
private static void sendMessageToAll(String msg) {
onlineSessions.forEach((id, session) -> {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



