我正在按照本教程建立与服务器的WebSocket连接: http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html
代码(与教程相同):
import java.net.URI;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
/**
* Example of a simple Echo Client.
*/
public class SimpleEchoClient {
public static void main(String[] args) {
String destUri = "ws://echo.websocket.org";
if (args.length > 0) {
destUri = args[0];
}
WebSocketClient client = new WebSocketClient();
SimpleEchoClient socket = new SimpleEchoClient();
try {
client.start();
URI echoUri = new URI(destUri);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket, echoUri, request);
System.out.printf("Connecting to : %s%n", echoUri);
// socket.awaitClose(5, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
错误:
2014-08-07 21:49:00.346:INFO::main: Logging initialized @86ms
org.eclipse.jetty.websocket.api.InvalidWebSocketException:
SimpleEchoClient is not a valid WebSocket object.
Object must obey one of the following rules:
(1) class implements org.eclipse.jetty.websocket.api.WebSocketListener or
(2) class is annotated with @org.eclipse.jetty.websocket.api.annotations.WebSocket
at org.eclipse.jetty.websocket.common.events.EventDriverFactory.wrap(EventDriverFactory.java:145)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:200)
at org.eclipse.jetty.websocket.client.WebSocketClient.connect(WebSocketClient.java:144)
at SimpleEchoClient.main(SimpleEchoClient.java:31)
我不太确定导入的jar文件有什么问题。也许这是错的?我正在使用这个:http://mvnrepository.com/artifact/org.eclipse.jetty.websocket/websocket-client/9.2.2.v20140723
当然必须有一种更简单的方法通过Jetty Websocket建立连接并开始接收数据?
答案 0 :(得分:0)
看起来您使用的当前版本的文档已过时。尝试回滚到更稳定的9.2.x版本,如:
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>9.2.0.RC0</version>
</dependency>
答案 1 :(得分:0)
正如Kayman在评论中解释的那样,你的套接字处理程序实现的问题,请使用这里用一个例子解释的最新版本(同样你使用但正确)http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html