import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class WebSocketHandler {
private static final Map<String, Channel> sessionMap = new ConcurrentHashMap<>();
@Autowired
private ApplicationContext applicationContext;
public void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
if (!req.decoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
String sessionId = req.headers().get("Sec-WebSocket-Key");
ctx.channel().attr(WebSocketSessionManager.SESSION_KEY).set(sessionId);
WebSocketSessionManager.addSession(sessionId, ctx.channel());
// 这里省略了WebSocket握手相关代码
}
public void sendMessageToClient(String sessionId, String message) {
Channel channel = sessionMap.get(sessionId);
if (channel == null) {
return;
}
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeCharSequence(message, StandardCharsets.UTF_8);
channel.writeAndFlush(byteBuf);
}
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {
if (res.status().code() != 200) {
ByteBuf byteBuf = Unpooled.copiedBuffer(res.status().toString(), StandardCharsets.UTF_8);
res.content().writeBytes(byteBuf);
byteBuf.release();
评论已关闭