我看到了很多关于如何使用某种嵌入式web服务器设置JSR356网络套接字的教程
但我想在部署到独立码头安装的现有WAR中添加一些websocket,即jetty-9.2.3.v20140905,我能找到的关于这方面的信息很少。我不知道是什么阻碍了它的工作。据我所知,带注释的服务器端点应该由jetty自动处理。
服务器端点:
@ServerEndpoint(value = "/myendpoint")
public class MyServerEndpoint {
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session s) {
logger.info("Server Connected ... " + s.getId());
s.getAsyncRemote().sendText("You are connected to the websocket server");
}
@OnMessage
public void onMessage(String message, Session session) {
// Sent the message back to all connected users
logger.info("Server Session " + session + " Received string message " + message);
for(Session s: session.getOpenSessions()) {
if (s.isOpen()) {
s.getAsyncRemote().sendText(message + " server response");
}
}
}
@OnClose
public void onClose(Session session, CloseReason reason) {
logger.info("Server Session " + session + " closed for reason " + reason);
}
}
ClientEndpoint:
@ClientEndpoint
public class MyClientEndpoint {
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session s) {
logger.info("Client Connected ... " + s.getId());
s.getAsyncRemote().sendText("hello from the client!");
}
@OnMessage
public void onMessage(String message, Session session) {
logger.info("Client Session " + session + " Received string message " + message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
logger.info("Client Session " + session + " closed for reason " + reason);
}
}
以下是将客户端连接到服务器的代码(在某些现有方法中运行)
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/myWar/myendpoint";
container.connectToServer(MyClientEndpoint.class, URI.create(uri));
然而,旋转码头在connectToServer线路上出现错误
2014-10-30 12:26:58.658:WARN:oeja.ServletContainerInitializersStarter:main:
org.eclipse.jetty.websocket.api.InvalidWebSocketException: Unable to instantiate websocket: class java.lang.Class
at org.eclipse.jetty.websocket.jsr356.ClientContainer.newClientEndpointInstance(ClientContainer.java:311)
at org.eclipse.jetty.websocket.jsr356.ClientContainer.connectToServer(ClientContainer.java:172)
我所能想到的就是URI不正确。如果jetty在8080上运行,我的.war名为myWar,我的终点名为myendpoint。。。这不是正确的URI吗?
是否必须执行一些附加步骤来"激活"服务器端点以侦听连接?我一定错过了什么显而易见的东西。
奇怪的是,你的错误消息。
org.eclipse.jetty.websocket.api.InvalidWebSocketException:
Unable to instantiate websocket: class java.lang.Class
这意味着websocket实现得到了一个要实例化的原始java.lang.Class。这行不通。
这也意味着没有尝试连接,因为WebSocket类本身非常糟糕,无法进行连接。
下面是一个简短的(有效且有效的)示例,展示了它的用途。
package jetty.jsr356;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class TestClientAnnotatedClass
{
private static CountDownLatch closeLatch = new CountDownLatch(1);
@OnOpen
public void onOpen(Session session)
{
System.out.println("@OnOpen - " + session);
try
{
session.getBasicRemote().sendText("Rock it with Java WebSocket");
}
catch (IOException e)
{
e.printStackTrace();
}
}
@OnMessage
public void onMessage(Session session, String msg)
{
System.out.println("@OnMessage - ["+msg+"]");
try
{
session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE,"Thanks"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
@OnClose
public void onClose(CloseReason close)
{
System.out.println("@OnClose - " + close);
closeLatch.countDown();
}
public static void main(String[] args)
{
try
{
WebSocketContainer ws = ContainerProvider.getWebSocketContainer();
ws.connectToServer(TestClientAnnotatedClass.class,new URI("ws://echo.websocket.org/?encoding=text"));
closeLatch.await();
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}
你会看到类似于这个的输出
2014-10-30 11:34:19.197:INFO::main: Logging initialized @71ms
@OnOpen - WebSocketSession[websocket=JsrAnnotatedEventDriver[websocket=jetty.jsr356.TestClientAnnotatedClass@5cca5f2c],behavior=CLIENT,connection=WebSocketClientConnection@6a2e714b{IDLE}{f=Flusher[queueSize=0,aggregateSize=0,failure=null],g=Generator[CLIENT,validating],p=Parser@55465b1f[ExtensionStack,s=START,c=0,len=0,f=null,p=WebSocketPolicy@7e087bf5[behavior=CLIENT,maxTextMessageSize=65536,maxTextMessageBufferSize=32768,maxBinaryMessageSize=65536,maxBinaryMessageBufferSize=32768,asyncWriteTimeout=60000,idleTimeout=300000,inputBufferSize=4096]]},remote=WebSocketRemoteEndpoint@5f025277[batching=true],incoming=JsrAnnotatedEventDriver[websocket=jetty.jsr356.TestClientAnnotatedClass@5cca5f2c],outgoing=ExtensionStack[queueSize=0,extensions=[],incoming=org.eclipse.jetty.websocket.jsr356.JsrSession,outgoing=org.eclipse.jetty.websocket.client.io.WebSocketClientConnection]]
@OnMessage - [Rock it with Java WebSocket]
@OnClose - CloseReason[1000,Thanks]
Jetty使用反射创建带注释的客户端端点的实例(请参见/Jetty/websocket/jsr356/ClientContainer#newClientEndpointInstance()),但Java无法以这种方式实例化非静态内部类。实际原因异常类似于java.lang.NoSuchMethodException: <pkg>.OuterClass$InnerClass.<init>()
,但它被吞噬了。
解决方案:带注释的端点类不应该是嵌套或嵌套的静态(内部)类。