直接改用netty-websocket-spring-boot-starter !
更换依赖
<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.11.0</version>
</dependency>
若出现错误,请注意导入的包是否正确,特别是注解。
参考代码:
package windbody.wemind.quickcalculationcenter.practicemode.service.game;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import io.netty.handler.codec.http.HttpHeaders;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;
import redis.clients.jedis.Jedis;
import windbody.wemind.securitycontrolcenter.resource.util.CustomJwtResult;
import windbody.wemind.securitycontrolcenter.resourcemanager.compute.UserCredentialsManager;
/**
* @author zhengkai.blog.csdn.net
*/
@ServerEndpoint(path ="/calGameServer",port = "40003")
@Component
public class WebSocketServer {
private Long userId;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private UserCredentialsManager userCredentialsManager;
@Autowired
private Jedis jedis;
static Logger log= LoggerFactory.getLogger(WebSocketServer.class);
private Session session;
/**接收userId*/
// @BeforeHandshake
// public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
// session.setSubprotocols("stomp");
// if (!"ok".equals(req)){
// System.out.println("Authentication failed!");
// session.close();
// }
// }
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
this.session = session;
String token= headers.get("access-token");
CustomJwtResult result=userCredentialsManager.verify("");
this.userId=result.getUserId();
//从redis获取在线用户列表
Map onlineUserMap=jedis.hgetAll("onlineUserMap");
if(onlineUserMap==null)
{
onlineUserMap=new HashMap();
}
//更新列表
onlineUserMap.put(userId,userId);
jedis.hset("onlineUserMap",onlineUserMap);
//更新/保持session
String sessionKey=userId+"session";
jedis.setex(sessionKey,12*60*60,new Gson().toJson(session));
log.info("用户连接:"+userId+",当前在线人数为:" + onlineUserMap.size());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+userId+",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) throws IOException {
Map map= jedis.hgetAll("onlineUserMap");
map.remove(this.userId);
jedis.hset("onlineUserMap",map);
log.info("用户退出:"+userId+",当前在线人数为:" + map.size());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(Session session, String message) {
log.info("用户消息:"+userId+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(StringUtils.isNotBlank(message)){
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
//jsonObject.put("fromUserId",this.userId);
// String toUserId=jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
String method=jsonObject.getString("method");
switch (method)
{
case "createRoom":createRoom();break;
case "ready":ready();break;
default:break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
private void createRoom() throws IOException {
//生成一个房间号
sendMessage(123+"");
}
private void ready(){
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.sendText(message);
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message, String userId) throws IOException {
log.info("发送消息到:"+userId+",报文:"+message);
}
}