java - 无法在 tomcat 8 上打开与 websocket 的连接

标签 java tomcat websocket

我有以下 ServerEndpoint,它只不过是一个测试:

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/echo")
public class EchoService {

 /**
 * @OnOpen allows us to intercept the creation of a new session.
 * The session class allows us to send data to the user.
 * In the method onOpen, we'll let the user know that the handshake was 
 * successful.
 */
@OnOpen
public void onOpen(Session session){
    System.out.println(session.getId() + " has opened a connection"); 
    try {
        session.getBasicRemote().sendText("Connection Established");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

/**
 * When a user sends a message to the server, this method will intercept the message
 * and allow us to react to it. For now the message is read as a String.
 */
@OnMessage
public void onMessage(String message, Session session){
    System.out.println("Message from " + session.getId() + ": " + message);
    try {
        session.getBasicRemote().sendText(message);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

/**
 * The user closes the connection.
 * 
 * Note: you can't send messages to the client from this method
 */
@OnClose
public void onClose(Session session){
    System.out.println("Session " +session.getId()+" has ended");
}

}

现在我正在尝试使用 Simple Websocket Client Chrome Extension 连接到它, 但它永远无法连接。

我认为这可能与我使用 Tomcat 8 作为 servlet 容器有关。我将此依赖项添加到我的 pom.xml

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.0</version>
    <scope>provided</scope>
</dependency>

请注意,由于 tomcat 8 带有 websocket api,因此我将其设置为提供的。 我想知道我是否应该在我的 web.xml 中添加一些东西,但是找不到任何相关的东西..

我尝试连接的 URI 是 ws://localhost:8080/ecommerce-view/echo 因为我的项目 war 被命名为 ecommerce-view

欢迎任何帮助。

最佳答案

尝试使用 @ServerEndpoint("/echo")。因此,删除 value=

关于java - 无法在 tomcat 8 上打开与 websocket 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30877257/

相关文章:

django - “WebSocketProtocol”对象没有属性 'application_queue' 错误 Django Channels

java - 如果行之间存在多个间隙,如何从输入文件中读取所有行?

java - 如何使用环境变量将 JVM 参数传递给 Teamcity

java - 通过从命令行安装 tomcat 7 maven 插件来下载 spring petclinic

tomcat - 替换某些元素但保持剩余 XML 文档完好无损的样式表

java - 如何在外部 Tomcat 服务器中运行 WAR 文件的设置代码

java - 为什么我收到错误 "ERROR Could not find value for key log4j.appender.CONSOLE"?

java - 使用 JNI 为简单的基本程序编译 dll 时出现 gcc 错误

javascript - 为什么使用不同电脑时 "WebRTC Screen sharing"不流?

javascript - 网络套接字握手。从 ws 到 wss