【问题标题】:Unable to open connection with websocket on tomcat 8无法在tomcat 8上打开与websocket的连接
【发布时间】:2015-06-16 20:12:40
【问题描述】:

我有以下 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,因为我的项目战争被命名为 ecommerce-view

欢迎任何帮助。

【问题讨论】:

    标签: java tomcat websocket


    【解决方案1】:

    试试@ServerEndpoint("/echo")。所以,删除value=

    【讨论】:

    • 嗯..我尝试使用相同的 EchoService、相同的依赖项和相同的 chrome 插件复制您的项目,并且一切正常。所以,代码明智的似乎很好。你的 EchoService 在 src/main/java 目录中吗? tomcat 日志中有什么奇怪的地方吗?
    • 是和否,没有记录,也许我的问题是 web.xml 上的问题,我明天会用该文件的内容更新问题
    猜你喜欢
    • 2020-10-26
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多