我使用tomcat 7.0.53来制作websocket代码,当我使用a/用于websocket位置时,错误代码200,当我使用/echo用于websocket位置时,错误代码404。我不知道为什么它不工作。下面是我的程序的html和java端代码。
Java: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: <!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>
网址为http://localhost:8080/websocket/
。但是在代码
var ws = new WebSocket("ws://localhost:8080/echo");
使用代替正确的方法var ws = new WebSocket("ws://localhost:8080/websocket/echo");
。在此之后,握手和与套接字的通信正常工作。