我尝试了一个简单的websocket应用程序,但它给出了一个错误,
WebSocket connection to 'ws://localhost:8080/WebSocketPrj02/chatroomServerEndpoint' failed: Error during WebSocket handshake: Unexpected response code: 404
我发现很多关于同一主题的讨论,但它并没有帮助我,这就是我发布新问题的原因。
我的文件是, 的 ChatroomServerEndpoint.java
package com.za.tutorial.websocket;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("chatroomServerEndpoint")
public class ChatroomServerEndpoint {
static Set<Session> chatroomUsers = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void handleOpen(Session userSession){
chatroomUsers.add(userSession);
}
@OnMessage
public void handleMessage(String message, Session userSession) throws IOException{
String userName = (String) userSession.getUserProperties().get("userNmae");
if(userName == null){
userSession.getUserProperties().put("userName", userName);
userSession.getBasicRemote().sendText(buildJsonData("System"," you are connected as "+message));
} else {
Iterator<Session> iterator = chatroomUsers.iterator();
while(iterator.hasNext()){
iterator.next().getBasicRemote().sendText(buildJsonData(userName, message));
}
}
}
private String buildJsonData(String userName, String message) {
JsonObject jsonObject = Json.createObjectBuilder().add("message", userName+": "+message).build();
StringWriter stringWriter = new StringWriter();
try(JsonWriter jsonWriter = Json.createWriter(stringWriter)){
jsonWriter.write(jsonObject);
}
return stringWriter.toString();
}
}
default.html中
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Websocket2</title>
<script type="text/javascript">
var websocket = new WebSocket("ws://localhost:8080/WebSocketPrj02/chatroomServerEndpoint")
websocket.onmessage = function processMessage(message) {
var jsonData = JSON.parse(message.data);
if(jsonData.message != null){
messagesTextArea.value += jsonData.message +"\n";
}
}
function sendMessage() {
websocket.send(messageText.value);
messageText.value = "";
}
</script>
</head>
<body>
<textarea id="messagesTextArea" readonly="readonly" rows="10" cols="45"></textarea><br>
<input type = "text" id="messageText" size="50">
<input type="button" value="send" onclick="sendMessage();">
</body>
</html>
我正在使用Spring Tool Suit,apache-tomcat-7.0.37。 我查看了相关堆栈溢出帖子中给出的所有建议,但仍然无法正常工作。 我知道它很简单,但仍然给出错误。我完全被困在这里。可以请任何人帮助我吗??
答案 0 :(得分:0)
最后问题解决了。我刚刚从Eclipse切换到Netbeans,从Apache tomcat切换到Glassfish,现在它对我来说很好。