SpringBoot WebSocket实现 web页面聊天

1.导入websock所需要的pom文件

   
      org.springframework.boot
      spring-boot-starter-websocket
      1.3.5.RELEASE
   

2.config需要配置文件



import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/endpointChat").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue");
    }
}

 

3.创建socket需要工具类


import com.seage.commons.utils.SeageUtils;
import com.seage.tjsafety.common.entity.data.DataOperationLog;
import com.seage.tjsafety.dao.DataDao;
import com.seage.tjsafety.service.project.service.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class SocketUtil {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private DataService dataService;

    /**              。。。。。。。。。。。。。。①
     * 发送需要调用方法
     * @param msg 发送消息
     */
    @MessageMapping("/chat")
    public void handleChat(String msg){
        System.out.println("执行发送方法,接收人  admin  接收信息"+msg);
        String uname="admin";
        rebackRunDataMess(msg,uname);
    }


    /**              。。。。。。。。。。。。。②
     * 修改信息后返回给其他用户有关修改信息
     * @param dataOperationLog 操作Logger对象信息
     */
    public void revertOpinionMess(DataOperationLog dataOperationLog,String acceptName,String userName) throws Exception{
        //所有用户发送消息
        if(!isEmpty(acceptName)){
            simpMessagingTemplate.convertAndSendToUser(acceptName,"/queue/notifications",
                userName+dataOperationLog.getDetail());
        }else {
            throw new Exception("接收更改消息的姓名不能为空");
        }
    }
}

注释:

     1.方法一直接引入config文件后,调用改方法就可以直接执行,可以用来开发简单的,内容用户接受比较唯一的

     2.方法二是我需要给多个用户使用socket发送消息,所以这里直接就是一个类似于工具类,每一个用户发送信息要多次调用改方法

4.创建jsp页面


    
        
        聊天室
        
        
        
        
        <%----%>
    
    
    

聊天室

发送消息内容为:

注:

1.这个jsp页面实现了该用户发送消息,点击发送后消息返回

 

测试结果:

我调用的是SocketUtil.chat方法,登录的就直接是admin用户,发送消息返回给自己,实现简单的通讯

SpringBoot WebSocket实现 web页面聊天_第1张图片

SpringBoot WebSocket实现 web页面聊天_第2张图片

 

 

 

 

 

你可能感兴趣的:(后台,工具类)