Fork me on GitEE

WebSocket

socket config
package com.example.springbootmybatisredis.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
* ClassName:WebSocketConfig
* Package:com.example.springbootmybatisredis.conf
* Description:
*
* @date:2021/7/19 17:40
* @author:xy
*/
@Configuration
public class WebSocketConfig {

/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}


Controller


package com.example.springbootmybatisredis.controller;

import com.alibaba.fastjson.JSON;
import com.example.springbootmybatisredis.dto.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
* ClassName:WebSocketController
* Package:com.example.springbootmybatisredis.controller
* Description:
*
* @date:2021/7/19 17:46
* @author:xy
*/
/**
* 前后端交互的类实现消息的接收推送(自己发送给另一个人)
*
* @ServerEndpoint(value = "/test/oneToOne") 前端通过此URI 和后端交互,建立连接
*/
@Slf4j
@ServerEndpoint(value = "/test/oneToOne")
@Component
public class OneToOneWebSocket {

/** 记录当前在线连接数 */
private static AtomicInteger onlineCount = new AtomicInteger(0);

/** 存放所有在线的客户端 */
private static Map<String, Session> clients = new ConcurrentHashMap<>();

/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
onlineCount.incrementAndGet(); // 在线数加1
clients.put(session.getId(), session);
log.info("有新连接加入:{},当前在线人数为:{}", session.getId(), onlineCount.get());
}

/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
onlineCount.decrementAndGet(); // 在线数减1
clients.remove(session.getId());
log.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
}

/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
try {
Message myMessage = JSON.parseObject(message, Message.class);
if (myMessage != null) {
Session toSession = clients.get(myMessage.getUserId());
if (toSession != null) {
this.sendMessage(myMessage.getMessage(), toSession);
}
}
} catch (Exception e) {
log.error("解析失败:{}", e);
}
}

@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}

/**
* 服务端发送消息给客户端
*/
private void sendMessage(String message, Session toSession) {
try {
log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
toSession.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("服务端发送消息给客户端失败:{}", e);
}
}

}

传递dto对象
package com.example.springbootmybatisredis.dto;

/**
* ClassName:message
* Package:com.example.springbootmybatisredis.dto
* Description:
*
* @date:2021/7/19 18:30
* @author:xy
*/
import lombok.Data;
@Data
public class Message {
String message;
String userId;
}
HTML 自测页面
package com.example.springbootmybatisredis.conf;

import com.example.springbootmybatisredis.SpringbootmybatisredisApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* ClassName:html
* Package:com.example.springbootmybatisredis.conf
* Description:
*
* @date:2021/7/19 18:09
* @author:xy
*/
@SpringBootApplication
public class html implements WebMvcConfigurer {

public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisredisApplication.class, args);
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}

}
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
 yml
resources:
static-locations: classpath:/templates/





posted @ 2021-07-20 11:58  问道于盲  阅读(48)  评论(0编辑  收藏  举报