我是WebSockets
的新手。为了开始学习,我遵循了this教程。并只需复制ClientEndpoint
和ServerEndpoint
并使用tyrus
部署服务器。
但是当我尝试运行服务器时,它将抛出此错误:
Failed to load container provider class: org.glassfish.tyrus.container.grizzly.GrizzlyEngine
这是部署代码(我已经注释了发生错误的那一行):
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.glassfish.tyrus.server.Server;
public class WebSocketServer {
public static void main(String[] args) {
runServer();
}
public static void runServer() {
Server server = new Server("localhost", 8000, "/websockets", WordgameServerEndpoint.class);
try {
server.start(); //i get the error on this line
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please press a key to stop the server.");
reader.readLine();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
server.stop();
}
}
}
这是服务器代码:
import java.io.IOException;
import java.util.logging.Logger;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/game")
public class WordgameServerEndpoint {
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
logger.info("Connected ... " + session.getId());
}
@OnMessage
public String onMessage(String message, Session session) {
switch (message) {
case "quit":
try {
session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Game ended"));
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
}
return message;
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason));
}
}
我将不胜感激:)
最佳答案
这似乎是一个依赖问题,
如果您是maven用户:
<dependencies>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-server</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
或加载以下罐子:
grizzly-framework-2.3.3.jar
grizzly-http-2.3.3.jar
grizzly-http-server-2.3.3.jar
grizzly-rcm-2.3.3.jar
javax.websocket-api-1.0.jar
tyrus-client-1.1.jar
tyrus-container-grizzly-1.1.jar
tyrus-core-1.1.jar
tyrus-server-1.1.jar
tyrus-spi-1.1.jar
tyrus-websocket-core-1.1.jar
请记住,客户端和服务器实现都需要依赖。