我在我的应用程序中使用 Jetty 9.0.2.v20130417(在 Java 1.7 下)
小服务程序:
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class WSServletHandler extends WebSocketServlet
{
private static final long serialVersionUID = 6600543852415589642L;
public static class WSCustomCreator implements WebSocketCreator
{
@Override
public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp)
{
return new WSSocketHandler();
}
}
@Override
public void configure(WebSocketServletFactory factory)
{
factory.setCreator(new WSCustomCreator());
}
}
Websocket 处理程序:
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.api.WebSocketException;
public class WSSocketHandler extends WebSocketAdapter
{
public WSSocketHandler()
{
System.out.println("+++ Websocket class constructor");
}
public void onWebSocketConnect(Session sess)
{
System.out.println("+++ Websocket Connect from " + sess.getRemoteAddress().getAddress());
}
@Override
public void onWebSocketError(Throwable e)
{
System.out.println("+++ Websocket Error " + e.getMessage());
e.printStackTrace();
}
@Override
public void onWebSocketClose(int statusCode, String reason)
{
System.out.println("+++ Websocket close " + statusCode + " , " + reason);
}
public void onWebSocketException(WebSocketException e)
{
System.out.println("+++ Websocket Exception " + e.getMessage());
e.printStackTrace();
}
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len)
{
System.out.println("+++ ignoring binary message");
}
@Override
public void onWebSocketText(String message)
{
System.out.println("+++ MESSAGE: " + message);
if (isNotConnected())
{
System.out.println("+++ not connected");
return;
}
try {
getRemote().sendString("lallo");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我可以从 javascript 连接到码头服务器,我可以从 js 向码头发送消息。我在 onWebSocketText 函数中看到了这条消息。问题: isNotConnected() 始终为真,因此没有任何内容返回浏览器。我在浏览器中的 Jetty 或 Javascript 中没有收到任何错误。
码头日志: http: //pastebin.com/Qq2EynFJ
我的想法已经不多了......我很确定我错过了一些重要的东西,但是:我在 java 下进行了类似的测试,其中的 jetty 和 java 版本完全相同。唯一的区别是上面的代码是一个更大的应用程序的一部分,而简短的测试是一个独立的程序。
提前致谢