WebSocketListener 可以提供 beforeWebSocketConnect 方法吗?
我想在打开套接字之前检查请求参数是否正确,如果不正确则拒绝连接。
但是,有没有办法取消协议切换?
从 Jetty 9 开始,您可以使用WebSocketCreator概念来实现此行为。
package org.eclipse.jetty.websocket.server.examples;
import java.io.IOException;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.eclipse.jetty.websocket.server.examples.echo.BigEchoSocket;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
@SuppressWarnings("serial")
public class MyCustomCreationServlet extends WebSocketServlet
{
public static class MyCustomCreator implements WebSocketCreator
{
@Override
public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp)
{
String query = req.getQueryString();
// Start looking at the UpgradeRequest to determine what you want to do
if ((query == null) || (query.length() <= 0))
{
try
{
// Let UPGRADE request for websocket fail with
// status code 403 (FORBIDDEN) [per RFC-6455]
resp.sendForbidden("Unspecified query");
}
catch (IOException e)
{
// An input or output exception occurs
e.printStackTrace();
}
// No UPGRADE
return null;
}
// Create the websocket we want to
if (query.contains("bigecho"))
{
return new BigEchoSocket();
}
else if (query.contains("echo"))
{
return new MyEchoSocket();
}
// Let UPGRADE fail with 503 (UNAVAILABLE)
return null;
}
}
@Override
public void configure(WebSocketServletFactory factory)
{
factory.setCreator(new MyCustomCreator());
}
}