引入Maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
配置config
新建config文件夹,编写WebSocketConfig类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
编写WebSocketService类
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
// //连接打开时执行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// }
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
编写你要发送内容的Java类,我用的是一个Controller,访问这个接口直接
发送socket消息给用户
@RestController
@RequestMapping(value = "/socket/api/", produces = "text/html;charset=utf-8")
public class SocketApiController {
@Autowired
private NjkUserMapper userMapper;
@Autowired
private InquiryMapper inquiryMapper;
@Autowired
private NjkUserServiceMapper njkUserServiceMapper;
@Autowired
private WebSocketServer webSocketServer;
@PostMapping("sendToUser")
public String sendToUser(String type, String userId, String orderNum) {
try {
InquiryEntity inquiryEntity = new InquiryEntity();
inquiryEntity.setInquiryStatus(0);
inquiryEntity.setCreateTime(new Date());
inquiryEntity.setUserId(userId);
inquiryEntity.setProductId(orderNum);
inquiryMapper.insert(inquiryEntity);
NjkUserEntity njkUserEntity = userMapper.selectByPrimaryKey(userId);
Example example = new Example(NjkUserServiceEntity.class);
example.createCriteria().andEqualTo("serviceId", njkUserEntity.getServiceId());
NjkUserServiceEntity njkUserServiceEntity = njkUserServiceMapper.selectOneByExample(example);
if (njkUserServiceEntity != null && !"".equals(njkUserServiceEntity)) {
String message = "";
if ("1".equals(type)) {
message = njkUserServiceEntity.getName() + ",请注意,客户\'" + njkUserEntity.getNickName() + "\'提交了VIP申请信息,请及时处理以及回馈!联系方式:" + njkUserEntity.getPhone();
message = "{\"type\":\"1\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";
} else if ("2".equals(type)) {
message = njkUserServiceEntity.getName() + ",请注意,客户\'" + njkUserEntity.getNickName() + "\'提交了咨询信息,请及时处理以及回馈!联系方式:" + njkUserEntity.getPhone();
message = "{\"type\":\"2\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";
} else if ("3".equals(type)) {
message = njkUserServiceEntity.getName() + ",请注意,客户\'" + njkUserEntity.getNickName() + "\'支付了订单,请及时处理以及回馈!订单号为:" + orderNum;
message = "{\"type\":\"3\",\"msg\":\"" + message + "\",\"serviceId\":\""+njkUserEntity.getServiceId()+"\"}";
}
webSocketServer.sendInfo(message);
}
} catch (IOException e) {
e.printStackTrace();
return "失败";
} catch (Exception e) {
e.printStackTrace();
return "失败";
}
return "成功";
}
重要的地方在这两个地方
接下来就是测试WebSocket是否可用
我是直接上这个网址去测试的websocket在线测试
测试图
通过前端代码
socket = new WebSocket("ws://localhost:9997/appManager/websocket");
其中,appManager是工程名,/webscoket是访问路径名
建立连接,前端调用scoket.open() 会使后台在静态成员变量webSocketSet里面增加一个元素,相当于一个缓存。后台服务调用sendMessage
(指定某个用户,定向)或sendInfo(遍历webSocketSet逐个发送,类似群发)方法,即可向已登录的客户端推送消息。