2017-08-31 91 views
0

我提出兩類:的WebSocket具有嵌入Tomcat是404

  1. 與網頁套接字的嵌入的Tomcat(20年5月8日)
  2. ServerEndpoint Main類

我上IntelliJ IDEA的運行的主類 並在谷歌瀏覽器的控制檯中運行此JavaScript:new WebSocket('ws://localhost:8080/ws')

我預期的響應代碼是200,但實際上它是404

我怎樣才能解決這個問題?

主要類:

package webapp; 


import org.apache.catalina.LifecycleException; 
import org.apache.catalina.startup.Tomcat; 

import javax.servlet.ServletException; 
import java.io.File; 

public class Main { 
    private static final String STATIC_DIR = "src/main/static/"; 

    public static void main(String[] args) throws ServletException, LifecycleException { 
     Tomcat tomcat = new Tomcat(); 
     tomcat.setPort(8080); 

     File staticDir = new File(STATIC_DIR); 
     tomcat.addWebapp("/", staticDir.getAbsolutePath()); 

     tomcat.start(); 
     tomcat.getServer().await(); 
    } 
} 

ServerEndpoint:

package webapp.websocket; 

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

@ServerEndpoint("/ws") 
public class SampleWebSocket { 

    @OnOpen 
    public void onOpen(Session session) { 
     System.out.println("open"); 
    } 


    @OnClose 
    public void onClose(Session session) { 
     System.out.println("close"); 
    } 

    @OnMessage 
    public String onMessage(String text) { 
     System.out.println("message:" + text); 
     return "Server:" + text; 
    } 
} 

謝謝。

回答

0

我找到了解決方案。 這個問題是複製的。

我讀Got 404 error on tomcat 7.0.47 websocket並編輯我的pom.xml。

以下是我的整個pom.xml。

<project xmlns="http://maven.apache.org/POM/4.0.0" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>com.example</groupId> 
    <artifactId>websocket-sample</artifactId> 
    <version>1.0.0-SNAPSHOT</version> 
    <name>websocket-sample</name> 

    <properties> 
     <java.version>1.8</java.version> 
     <maven.compiler.target>${java.version}</maven.compiler.target> 
     <maven.compiler.source>${java.version}</maven.compiler.source> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>org.apache.tomcat.embed</groupId> 
      <artifactId>tomcat-embed-core</artifactId> 
      <version>8.5.20</version> 
     </dependency> 
     <dependency> 
      <groupId>org.apache.tomcat</groupId> 
      <artifactId>tomcat-websocket</artifactId> 
      <version>8.5.20</version> 
     </dependency> 
     <dependency> 
      <groupId>javax.websocket</groupId> 
      <artifactId>javax.websocket-api</artifactId> 
      <version>1.1</version> 
     </dependency> 
    </dependencies> 
</project>