我确实对 jetty 8 websockets 有一个奇怪的问题。我发现几个教程几乎显示了相同的代码,但是当我尝试从本地 html 页面打开 websocket 时出现此错误:
2013-02-05 13:14:03.467:INFO:oejs.Server:jetty-8.1.9.v20130131
2013-02-05 13:14:03.770:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080
2013-02-05 13:14:18.002:WARN:oejs.ServletHandler:/echo
java.lang.NullPointerException
at org.eclipse.jetty.websocket.WebSocketFactory.upgrade(WebSocketFactory.java:236)
at org.eclipse.jetty.websocket.WebSocketFactory.acceptWebSocket(WebSocketFactory.java:382)
at org.eclipse.jetty.websocket.WebSocketServlet.service(WebSocketServlet.java:104)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:457)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
这是套接字 servlet:
public class ExampleWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
/**
* @see WebSocketServlet#WebSocketServlet()
*/
public ExampleWebSocketServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("OK");
out.close();
System.out.println("OK");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().getNamedDispatcher("default").forward(request, response);
}
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new EchoWebSocket();
}
}
和 WebSocket(用于简单的 Echo)
public class EchoWebSocket implements WebSocket.OnTextMessage {
private Connection con;
@Override
public void onClose(int closeCode, String message) {
}
@Override
public void onOpen(Connection con) {
this.con = con;
try {
con.sendMessage("Server received Web Socket upgrade ...");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String msg) {
System.out.println("Received: "+msg);
try {
con.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //send it back
}
}
我的 html 页面适用于其他 websocket 测试服务器,例如 websocket.org
有什么问题?我在 Eclipse 上,创建了一个动态 Web 项目并使用 jetty webapp 运行配置。此外,当码头启动时,我可以看到
/Users/sven.haiges/dev/jetty/jetty-distribution-8.1.9.v20130131/lib/jetty-websocket-8.1.9.v20130131.jar
在类路径上。
任何帮助表示赞赏,谢谢!