简体   繁体   中英

Error code 200 and 404 websocket on tomcat 7.0.53

I am using tomcat 7.0.53 to make websocket code and keep getting error code 200 when I use a / for the websocket location and error code 404 when I use /echo for the websocket location. I have no clue why it is not working. Below is the code for my programs html and java side.

Java side:

package wsapp;

import java.io.IOException;
import java.util.ArrayList;

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 WsChat{
//notice:not thread-safe
private static ArrayList<Session> sessionList = new ArrayList<Session>();

@OnOpen
public void onOpen(Session session){
    try{
        sessionList.add(session);
        //asynchronous communication
        session.getBasicRemote().sendText("Hello!");
    }catch(IOException e){}
}

@OnClose
public void onClose(Session session){
    sessionList.remove(session);
}

@OnMessage
public void onMessage(String msg){
    try{
        for(Session session : sessionList){
            //asynchronous communication
            session.getBasicRemote().sendText(msg);
        }
    }catch(IOException e){}
}
}

HTML Side:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Tomcat WebSocket Chat</title>
    <script>
        var ws = new WebSocket("ws://localhost:8080/echo");
        ws.onopen = function(){
        };
        ws.onmessage = function(message){
            document.getElementById("chatlog").textContent += message.data + "\n";
        };
        function postToServer(){
            ws.send(document.getElementById("msg").value);
            document.getElementById("msg").value = "";
        }
        function closeConnect(){
            ws.close();
        }
    </script>
</head>
<body>
    <textarea id="chatlog" readonly></textarea><br/>
    <input id="msg" type="text" />
    <button type="submit" id="sendButton" onClick="postToServer()">Send!</button>
    <button type="submit" id="sendButton" onClick="closeConnect()">End</button>
</body>

The URL for the website was http://localhost:8080/websocket/ . However in the code

var ws = new WebSocket("ws://localhost:8080/echo");

is being used instead of the correct way which is var ws = new WebSocket("ws://localhost:8080/websocket/echo"); . After that is done the handshake and communicating with the sockets works correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM