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页面
聊天室
<%----%>
聊天室
发送消息内容为: