栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

WebSocket实现聊天室业务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WebSocket实现聊天室业务

WebSocket实现聊天室业务的具体代码,供大家参考,具体内容如下

页面效果图

pom.xml

主要是spring-boot-starter-websocket包,websocket连接、发送信息。


   org.springframework.boot
   spring-boot-starter-web
  
  
   org.springframework.boot
   spring-boot-starter-websocket
  
  
   org.springframework.boot
   spring-boot-starter-thymeleaf
  
  
   org.webjars
   webjars-locator-core
  
  
   org.webjars.npm
   mdui
   0.4.0
  
  
   org.webjars
   jquery
   3.3.1
  
  
   org.springframework.boot
   spring-boot-devtools
   runtime
  
  
   com.alibaba
   fastjson
   1.2.49
  
  
   org.springframework.boot
   spring-boot-starter-test
   test

前台

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();
   }
  });
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号