使用原生的 javax.websocket 实现websocket - Go语言中文社区

使用原生的 javax.websocket 实现websocket


 在websocket中获取httpsession对象

/**
 * @Title:GetHttpSessionConfigurator.java
 * @Description:Comment for created Java file
 * @author 张颖辉
 * @date 2018年3月8日下午6:48:00
 * @version 1.0 
 */
package rg.sso.websocket_anno;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

//import org.springframework.context.annotation.Configuration;


/**
 * @Title:GetHttpSessionConfigurator 获取session所在的 httpSession
 * @Description:Comment for created type
 * @author 张颖辉
 * @date 2018年3月8日下午6:48:00
 * @version 1.0
 */
//@Configuration//无需这个注解
public class GetHttpSessionConfigurator extends Configurator {
	@Override
	public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
		HttpSession httpSession = (HttpSession) request.getHttpSession();
		sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
	}
}

websocket消息处理类 

/**
 * @Title:WebSocketEndpoint.java
 * @Description:Comment for created Java file
 * @author 张颖辉
 * @date 2018年3月9日上午9:43:04
 * @version 1.0 
 */
package rg.sso.websocket_anno;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import rg.sso.vo.Msg4Ws;

/**
 * @Title:WebSocketEndpoint 请求处理类
 * @Description:Comment for created type 猜测应该 是多例的
 * @author 张颖辉
 * @date 2018年3月9日上午9:43:04
 * @version 1.0
 */
@ServerEndpoint(value = "/websocket", configurator = GetHttpSessionConfigurator.class)
public class WebSocketEndpoint {
	private static Logger logger = LoggerFactory.getLogger(WebSocketEndpoint.class);
	// 保存所有的用户session
	private static Map<String, Session> SESSION_MAP = new Hashtable<String, Session>();

	@OnOpen
	public void onOpen(Session session, EndpointConfig config) throws IOException {
		logger.info("【WebSocket原生】用户{}连接", session.getId());
		HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
		httpSession.setAttribute("scoketSessionId", session.getId());
		logger.info("【WebSocket原生】httpSessionId:{},sessionId:{}", httpSession.getId(),
				httpSession.getAttribute("scoketSessionId"));
		SESSION_MAP.put(session.getId(), session);
		// 发送sessionId给前端
		Msg4Ws<String> msg4Ws = new Msg4Ws<String>(10000, "ws的sessionId", session.getId());
		String message = new ObjectMapper().writeValueAsString(msg4Ws); // 转为json
		send2User(session, message);

	}

	@OnMessage
	public void onMessage(Session session, String message) {
		logger.info("【WebSocket原生】收到消息:" + message);
		String resultMsg = message + " received at server";
		logger.info("【WebSocket原生】返回信息:" + resultMsg);
		try {
			send2User(session, resultMsg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@OnError
	public void onError(Throwable t) {
		System.err.println("【WebSocket原生】出错了");
		t.printStackTrace();
	}

	@OnClose
	public void onClose(Session session, CloseReason reason) {
		logger.info("用户{}【WebSocket原生】退出链接:" + session.getId());
		SESSION_MAP.remove(session.getId());
	}

	/**
	 * 向指定用户发送消息
	 * 
	 * @param session
	 * 
	 * @param msg
	 * @throws IOException
	 */
	public static void send2User(Session session, String msg) throws IOException {
		session.getBasicRemote().sendText(msg);
	}

	/**
	 * 向指定用户发送消息
	 * 
	 * @param session
	 * 
	 * @param msg
	 * @throws IOException
	 */
	public static void send2User(String sessionId, String msg) throws IOException {
		SESSION_MAP.get(sessionId).getBasicRemote().sendText(msg);
	}

	/**
	 * 向所有用户发送
	 * 
	 * @param msg
	 * @throws IOException
	 */
	public static void send2All(String msg) throws IOException {
		for (Session session : SESSION_MAP.values()) {
			send2User(session, msg);
		}
	}
}

将来有时间弄清楚细节时再更新

有点疑惑,网上找的相关教程没有提到启动的原理,应该是tomcat会自动扫描带有@ServerEndpoint注解的类并执行监听

转载于:https://my.oschina.net/iyinghui/blog/1785149

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34221775/article/details/91948077
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-21 23:04:25
  • 阅读 ( 359 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢