Java 类io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory 实例源码
项目:java_learn
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) {
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:7777/websocket", null, false);
socketServerHandshaker = wsFactory.newHandshaker(req);
if (socketServerHandshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
socketServerHandshaker.handshake(ctx.channel(), req);
}
}
项目:zbus
文件:MessageCodec.java
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof FullHttpRequest){
FullHttpRequest req = (FullHttpRequest) msg;
//check if websocket upgrade encountered
if(req.headers().contains("Upgrade") || req.headers().contains("upgrade")) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req, ctx), null, true, 1024 * 1024 * 1024);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
return;
}
}
super.channelRead(ctx, msg);
}
项目:netty-book
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) throws Exception {
// 如果HTTP解码失败,返回HHTP异常
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
BAD_REQUEST));
return;
}
// 构造握手响应返回,本机测试
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:8080/websocket", null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
项目:netty4.0.27Learn
文件:AutobahnServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req)
throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
项目:brent-pusher
文件:NettyPusherServer.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
if (!req.getDecoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://websocket.url", null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
IPusherClient conn=(IPusherClient)ctx.channel();
String uri=req.getUri();
handshaker.handshake(ctx.channel(), req);
onOpen(conn, uri);
}
}
项目:netty-study
文件:WebSocketServerHandler.java
public void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
if (!req.getDecoderResult().isSuccess() || !"websocket".equals(req.headers().get("Upgrade"))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
// 构造握手响应返回,本机测试
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null,
false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
项目:simple-websocket-client
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
项目:modules-extra
文件:WebSocketRequestHandler.java
public void doHandshake(ChannelHandlerContext ctx, FullHttpRequest message)
{
WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory("ws://" + message.headers().get(HOST) + "/" + WEBSOCKET_ROUTE, null, false);
this.handshaker = handshakerFactory.newHandshaker(message);
if (handshaker == null)
{
this.log.info("client is incompatible!");
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
return;
}
this.log.debug("handshaking now...");
this.handshaker.handshake(ctx.channel(), message).addListener((ChannelFutureListener) future -> {
if (future.isSuccess())
{
log.debug("Success!");
}
else
{
log.debug("Failed!");
}
});
}
项目:laputa
文件:LaputaServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
if (webSocketPath.equals(req.uri())) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, true, MAX_FRAME_PAYLOAD_LENGTH
);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
return;
}
requestProcessor.handleRequest(ctx, req);
}
项目:socketio
文件:WebSocketHandler.java
private void handshake(final ChannelHandlerContext ctx, final FullHttpRequest req, final String requestPath) {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true, maxWebSocketFrameSize);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker != null) {
handshaker.handshake(ctx.channel(), req).addListener(
new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
final String sessionId = PipelineUtils.getSessionId(requestPath);
if (future.isSuccess()) {
ctx.channel().pipeline().addBefore(
SocketIOChannelInitializer.SOCKETIO_WEBSOCKET_HANDLER,
SocketIOChannelInitializer.WEBSOCKET_FRAME_AGGREGATOR,
new WebSocketFrameAggregator(maxWebSocketFrameSize));
connect(ctx, req, sessionId);
} else {
log.error("Can't handshake: {}", sessionId, future.cause());
}
}
});
} else {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
}
}
项目:Instantlogic
文件:InstantlogicRequestHandler.java
@Override
public void handleHttpRequest(final ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
if ("/api".equals(request.getUri().substring(0, 4))) {
getOrCreateTraveler(request);
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(request), null, false);
handshaker = wsFactory.newHandshaker(request);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), request).addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
nettyTraveler.registerWebsocket(ctx);
}
});
}
} else {
super.handleHttpRequest(ctx, request);
}
}
项目:nettythrift
文件:HttpThriftBufDecoder.java
/**
* handle WebSocket request,then, the the RPC could happen in WebSocket.
*
* @param ctx
* @param request
*/
protected void handleWebSocket(final ChannelHandlerContext ctx, FullHttpRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("handleWebSocket request: uri={}", request.uri());
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(request.uri(), null, true);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
return;
}
ChannelFutureListener callback = websocketHandshakeListener(ctx, request);
ChannelFuture future = handshaker.handshake(ctx.channel(), request);
if (callback != null) {
future.addListener(callback);
}
ChannelPipeline pipe = ctx.pipeline();
if (pipe.get(WebsocketFrameHandler.class) == null) {
pipe.addAfter(ctx.name(), "wsFrameHandler", new WebsocketFrameHandler(handshaker));
ChannelHandler handlerAws = pipe.get(AwsProxyProtocolDecoder.class);
if (handlerAws != null) {
pipe.remove(handlerAws);
}
pipe.remove(ctx.name());// Remove current Handler
}
}
项目:moonlight-mqtt
文件:WebSocketHandShaker.java
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
/**
* 当且仅当uri为指定path的时候,进行websocket通讯的升级
* */
if (uri.equals(req.uri())
//CONNECTION 字段的值为 UPGRADE, firefox上存在多个值的情况
&& req.headers().get(HttpHeaderNames.CONNECTION).contains(HttpHeaderValues.UPGRADE)
//UPGRADE 字段的值为 WEBSOCKET
&& HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))
) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
uri, subprotocols, true, 5 * 1024 * 1024);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
//不支持的协议
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
//握手结束后补充如下协议
handshaker.handshake(ctx.channel(), req);
}
return;
}
//错误的情况
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
}
项目:xockets.io
文件:WebSocketServerHandler.java
/**
* Handle hand shake.
*
* @param ctx the ctx
* @param req the req
*/
private void handleHandShake(ChannelHandlerContext ctx, FullHttpRequest req) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true, (int) Config.getInstance().getMaxSize());
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
dominoServer.onOpen(this.newWrapper(ctx), req);
}
}
项目:iofabric
文件:MessageWebsocketHandler.java
/**
* Handler to open the websocket for the real-time message websocket
*
* @param ChannelHandlerContext,
* FullHttpRequest
* @return void
*/
public void handle(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
String uri = req.getUri();
uri = uri.substring(1);
String[] tokens = uri.split("/");
String publisherId;
if (tokens.length < 5) {
LoggingService.logWarning(MODULE_NAME, " Missing ID or ID value in URL ");
return;
} else {
publisherId = tokens[4].trim().split("\\?")[0];
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
null, true, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
Hashtable<String, ChannelHandlerContext> messageSocketMap = WebSocketMap.messageWebsocketMap;
messageSocketMap.put(publisherId, ctx);
StatusReporter.setLocalApiStatus().setOpenConfigSocketsCount(WebSocketMap.messageWebsocketMap.size());
MessageBus.getInstance().enableRealTimeReceiving(publisherId);
LoggingService.logInfo(MODULE_NAME, "Handshake end....");
return;
}
项目:iofabric
文件:ControlWebsocketHandler.java
/**
* Handler to open the websocket for the real-time control signals
*
* @param ChannelHandlerContext,
* FullHttpRequest
* @return void
*/
public void handle(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
String uri = req.getUri();
uri = uri.substring(1);
String[] tokens = uri.split("/");
String id;
if (tokens.length < 5) {
LoggingService.logWarning(MODULE_NAME, " Missing ID or ID value in URL ");
return;
} else {
id = tokens[4].trim();
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
null, true, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
WebSocketMap.addWebsocket('C', id, ctx);
StatusReporter.setLocalApiStatus().setOpenConfigSocketsCount(WebSocketMap.controlWebsocketMap.size());
return;
}
项目:spring-cloud-stream-app-starters
文件:WebsocketSinkServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
logger.warn(String.format("Bad request: %s", req.getUri()));
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
logger.warn(String.format("Unsupported HTTP method: %s", req.getMethod()));
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// enable subclasses to do additional processing
if (!additionalHttpRequestHandler(ctx, req)) {
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory
= new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
WebsocketSinkServer.channels.add(ctx.channel());
}
}
项目:intellij-ce-playground
文件:WebSocketHandshakeHandler.java
private void handleWebSocketRequest(@NotNull final ChannelHandlerContext context, @NotNull FullHttpRequest request, @NotNull final QueryStringDecoder uriDecoder) {
WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://" + request.headers().getAsString(HttpHeaderNames.HOST) + uriDecoder.path(), null, false, NettyUtil.MAX_CONTENT_LENGTH);
WebSocketServerHandshaker handshaker = factory.newHandshaker(request);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(context.channel());
return;
}
if (!context.channel().isOpen()) {
return;
}
final Client client = new WebSocketClient(context.channel(), handshaker);
context.attr(ClientManager.CLIENT).set(client);
handshaker.handshake(context.channel(), request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ClientManager clientManager = WebSocketHandshakeHandler.this.clientManager.getValue();
clientManager.addClient(client);
MessageChannelHandler messageChannelHandler = new MessageChannelHandler(clientManager, getMessageServer());
BuiltInServer.replaceDefaultHandler(context, messageChannelHandler);
ChannelHandlerContext messageChannelHandlerContext = context.pipeline().context(messageChannelHandler);
context.pipeline().addBefore(messageChannelHandlerContext.name(), "webSocketFrameAggregator", new WebSocketFrameAggregator(NettyUtil.MAX_CONTENT_LENGTH));
messageChannelHandlerContext.attr(ClientManager.CLIENT).set(client);
connected(client, uriDecoder.parameters());
}
}
});
}
项目:netty-reactive-streams
文件:DefaultWebSocketHttpResponse.java
public DefaultWebSocketHttpResponse(HttpVersion version, HttpResponseStatus status,
Processor<WebSocketFrame, WebSocketFrame> processor,
WebSocketServerHandshakerFactory handshakerFactory) {
super(version, status);
this.processor = processor;
this.handshakerFactory = handshakerFactory;
}
项目:netty-reactive-streams
文件:DefaultWebSocketHttpResponse.java
public DefaultWebSocketHttpResponse(HttpVersion version, HttpResponseStatus status, boolean validateHeaders,
Processor<WebSocketFrame, WebSocketFrame> processor,
WebSocketServerHandshakerFactory handshakerFactory) {
super(version, status, validateHeaders);
this.processor = processor;
this.handshakerFactory = handshakerFactory;
}
项目:lambdatra
文件:WsAdapter.java
@Override
public boolean call(NettyHandler handler, ChannelHandlerContext ctx, FullHttpRequest req, Map<String, String> params) throws IOException {
WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(
String.format("ws://%s%s", req.headers().get(Names.HOST), pattern),
null,
true
).newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
WebSocket ws = getCallback().newInstance(new WrappedRequest<>(req, params, sessions));
if (ws instanceof WebSocket) {
Channel ch = handshaker.handshake(ctx.channel(), req).channel();
handler.onWsFrame(new WsBridge(handshaker, ch, ws));
ws.onOpen();
} else {
FullHttpResponse forbidden = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
ByteBufUtil.writeUtf8(forbidden.content(), "Forbidden.");
ctx.writeAndFlush(forbidden);
ctx.close();
}
}
return true;
}
项目:netty-rest
文件:WebSocketService.java
@Override
public void handle(RakamHttpRequest request) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(request), null, true);
handshaker = wsFactory.newHandshaker(request.getRequest());
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(request.context().channel());
} else {
HttpRequest request1 = request.getRequest();
DefaultFullHttpRequest defaultFullHttpRequest = new DefaultFullHttpRequest(request1.getProtocolVersion(), request1.getMethod(), request1.getUri());
defaultFullHttpRequest.headers().set(request1.headers());
handshaker.handshake(request.context().channel(), defaultFullHttpRequest);
onOpen(new WebSocketRequest(request));
}
}
项目:SPQR
文件:SPQRWebSocketServerHandler.java
/**
* Handles incoming http request pointing. Parts of the code were copied from {@linkplain http://netty.io} web socket server example.
* The origins may be found at: {@linkplain https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServerHandler.java}
* @param ctx
* @param req
*/
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
// handle bad requests as indicated by decoder
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// allow only GET methods to comply with REST spec as this is not about modifying content
// but receiving it ;-)
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
String wsLocation = "ws://" + req.headers().get(HOST) + WEBSOCKET_PATH;
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
wsLocation, null, true);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
项目:carbon-transports
文件:WebSocketInitMessageImpl.java
@Override
public HandshakeFuture handshake() {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest), null, true);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest);
return handleHandshake(handshaker, 0);
}
项目:carbon-transports
文件:WebSocketInitMessageImpl.java
@Override
public HandshakeFuture handshake(String[] subProtocols, boolean allowExtensions) {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest), getSubProtocolsCSV(subProtocols),
allowExtensions);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest);
return handleHandshake(handshaker, 0);
}
项目:carbon-transports
文件:WebSocketInitMessageImpl.java
@Override
public HandshakeFuture handshake(String[] subProtocols, boolean allowExtensions, int idleTimeout) {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest),
getSubProtocolsCSV(subProtocols), allowExtensions);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest);
return handleHandshake(handshaker, idleTimeout);
}
项目:carbon-transports
文件:WebSocketInitMessageImpl.java
@Override
public void cancelHandShake(int closeCode, String closeReason) {
try {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest), getSubProtocol(), true);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest);
ChannelFuture channelFuture =
handshaker.close(ctx.channel(), new CloseWebSocketFrame(closeCode, closeReason));
channelFuture.channel().close();
} finally {
isCancelled = true;
}
}
项目:activemq-artemis
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
String supportedProtocolsCSV = StringUtil.joinStringList(supportedProtocols, ",");
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(this.getWebSocketLocation(req), supportedProtocolsCSV, false, maxFramePayloadLength);
this.httpRequest = req;
this.handshaker = wsFactory.newHandshaker(req);
if (this.handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req);
handshake.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and
// wrap it in a binary web socket frame before letting the wsencoder send it on the wire
future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER);
} else {
// Handshake failed, fire an exceptionCaught event
future.channel().pipeline().fireExceptionCaught(future.cause());
}
}
});
}
}
项目:tsdblite
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
// Handle a bad request.
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
if ("/favicon.ico".equals(req.uri())) {
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
sendHttpResponse(ctx, req, res);
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, true);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
ctx.writeAndFlush(new TextWebSocketFrame("{\"session\" : \"" + ctx.channel().id().asShortText() + "\"}"));
}
}
项目:netty4study
文件:AutobahnServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req)
throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
req.release();
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
req.release();
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
req.release();
}
项目:trap
文件:WebSocketTransport.java
public ChannelHandler serverHandshake(ChannelHandlerContext ctx, FullHttpRequest msg)
{
this.ctx = ctx;
// Handshake
WebSocketServerHandshaker handshaker;
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(msg), null, true);
handshaker = wsFactory.newHandshaker(msg);
if (handshaker == null)
{
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
}
else
{
ChannelPromise promise = ctx.channel().newPromise();
promise.addListener(future -> {
if (promise.isSuccess())
{
this.notifyOpen();
}
else
{
this.notifyError();
}
});
handshaker.handshake(ctx.channel(), msg, null, promise);
}
return new MyChannelHandler((ctx1, frame) -> {
handshaker.close(ctx1.channel(), (CloseWebSocketFrame) frame.retain());
});
}
项目:adalightserver
文件:HttpServer.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendErrorResponse(ctx, req, BAD_REQUEST);
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendErrorResponse(ctx, req, FORBIDDEN);
return;
}
String path = req.getUri();
System.out.println("Server => Request: " + path);
try {
if (path.equals("/ws")) {
isWebSocket = true;
String wsLocation = getWebSocketLocation(ctx, req);
WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(
wsLocation, null, false, 64 * 1024).newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel())
.addListener(ChannelFutureListener.CLOSE);
} else {
handshaker.handshake(ctx.channel(), req);
// Push the initial state to the client.
// Do it from the server thread were it's safe
bossGroup.execute(() -> {
ctx.writeAndFlush(makeWebSocketEventFrame("stateChanged", lastState));
});
wsConnections.add(ctx.channel());
}
}
else {
handleStaticFileRequest(ctx, req, path);
}
} catch (Throwable e) {
sendErrorResponse(ctx, req, BAD_REQUEST);
}
}
项目:Surf
文件:HttpServerHandler.java
private void handleWebSocketHandshake(ChannelHandlerContext ctx, FullHttpRequest req){
String location = "ws://" + req.headers().get(HOST) + req.getUri();
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
location, null, false);
_handshaker = wsFactory.newHandshaker(req);
if (_handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
_handshaker.handshake(ctx.channel(), req);
}
}
项目:netty-netty-5.0.0.Alpha1
文件:AutobahnServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req)
throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
req.release();
return;
}
// Allow only GET methods.
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
req.release();
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
req.release();
}
项目:jooby
文件:NettyRequest.java
@SuppressWarnings("unchecked")
@Override
public <T> T upgrade(final Class<T> type) throws Exception {
if (type == NativeWebSocket.class) {
String protocol = ifSecure("wss", "ws");
String webSocketURL = protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
webSocketURL, null, true, wsMaxMessageSize);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
NettyWebSocket result = new NettyWebSocket(ctx, handshaker, (ws) -> {
handshaker.handshake(ctx.channel(), (FullHttpRequest) req)
.addListener(FIRE_EXCEPTION_ON_FAILURE)
.addListener(payload -> ws.connect())
.addListener(FIRE_EXCEPTION_ON_FAILURE);
});
ctx.channel().attr(NettyWebSocket.KEY).set(result);
return (T) result;
} else if (type == Sse.class) {
NettySse sse = new NettySse(ctx);
return (T) sse;
} else if (type == NativePushPromise.class) {
return (T) new NettyPush(ctx,
req.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()),
header("host").orElse(ip()), ifSecure("https", "http"));
}
throw new UnsupportedOperationException("Not Supported: " + type);
}
项目:top-traffic
文件:WebSocketServerHandler.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.uri(), null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
return;
}
try {
Channel ch = ctx.channel();
this.connection = this.newConnection(ctx, req);
handshaker.handshake(ch, req);
} catch (Exception e) {
logger.error("handshake error", e);
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED));
}
}
项目:Grapi
文件:WebSocketsServerProtocolUpdater.java
@Override
@SuppressWarnings("PMD.OnlyOneReturn")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
// Handle a bad request.
if (!req.decoderResult().isSuccess()) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
return;
}
// Allow only GET methods.
if (req.method() != GET) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
} else {
ctx.fireChannelRead(msg);
}
}
项目:TFWebSock
文件:WebSocketHandler.java
protected void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
// Handle a bad request.
if (!req.getDecoderResult().isSuccess()) {
httpFileHandler.sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
// If you're going to do normal HTTP POST authentication before upgrading the
// WebSocket, the recommendation is to handle it right here
if (req.getMethod() == HttpMethod.POST) {
httpFileHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN);
return;
}
// Allow only GET methods.
if (req.getMethod() != HttpMethod.GET) {
httpFileHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN);
return;
}
// Send the demo page and favicon.ico
if ("/".equals(req.getUri())) {
httpFileHandler.sendRedirect(ctx, "/index.html");
return;
}
// check for websocket upgrade request
String upgradeHeader = req.headers().get("Upgrade");
if (upgradeHeader != null && "websocket".equalsIgnoreCase(upgradeHeader)) {
// Handshake. Ideally you'd want to configure your websocket uri
String url = "ws://" + req.headers().get("Host") + "/marketdata";
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(url, null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
}
else {
handshaker.handshake(ctx.channel(), req);
}
}
else {
boolean handled = handleREST(ctx, req);
if (!handled) {
httpFileHandler.sendFile(ctx, req);
}
}
}
项目:SurvivalMMO
文件:WebSocketHandler.java
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object req) throws Exception {
if (req instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) req;
// ----- Client authenticity check code -----
// !!!!! WARNING !!!!!
// THE BELOW SECTION OF CODE CHECKS TO ENSURE THAT CONNECTIONS ARE COMING
// FROM THE OFFICIAL AGAR.IO CLIENT. IF YOU REMOVE OR MODIFY THE BELOW
// SECTION OF CODE TO ALLOW CONNECTIONS FROM A CLIENT ON A DIFFERENT DOMAIN,
// YOU MAY BE COMMITTING COPYRIGHT INFRINGEMENT AND LEGAL ACTION MAY BE TAKEN
// AGAINST YOU. THIS SECTION OF CODE WAS ADDED ON JULY 9, 2015 AT THE REQUEST
// OF THE AGAR.IO DEVELOPERS.
/*String origin = request.headers().get(HttpHeaders.ORIGIN);
if (origin != null) {
switch (origin) {
case "http://agar.io":
case "https://agar.io":
case "http://localhost":
case "https://localhost":
case "http://127.0.0.1":
case "https://127.0.0.1":
break;
default:
ctx.channel().close();
return;
}
}*/
// -----/Client authenticity check code -----
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://" + request.headers().get(HttpHeaders.HOST) + "/", null, true);
handshaker = wsFactory.newHandshaker(request);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), request);
}
} else if (req instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame) req;
if (req instanceof CloseWebSocketFrame) {
if (handshaker != null) {
handshaker.close(ctx.channel(), ((CloseWebSocketFrame) req).retain());
}
} else if (req instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
} else {
ctx.fireChannelRead(frame.retain());
}
}
}
项目:FFS-PubSub
文件:WebSocketHandler.java
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object req) throws Exception {
if (req instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) req;
// ----- Client authenticity check code -----
/*String origin = request.headers().get(HttpHeaders.ORIGIN);
if (origin != null) {
switch (origin) {
case "http://localhost":
case "https://localhost":
case "http://127.0.0.1":
case "https://127.0.0.1":
break;
default:
ctx.channel().close();
return;
}
}*/
// -----/Client authenticity check code -----
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://" + request.headers().get(HttpHeaders.HOST) + "/", null, true);
mHandshaker = wsFactory.newHandshaker(request);
if (mHandshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
mHandshaker.handshake(ctx.channel(), request);
}
} else if (req instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame) req;
if (req instanceof CloseWebSocketFrame) {
if (mHandshaker != null) {
mHandshaker.close(ctx.channel(), ((CloseWebSocketFrame) req).retain());
}
} else if (req instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
} else {
ctx.fireChannelRead(frame.retain());
}
}
}