我在跑步:
雄猫7
Java版本1.8
Chrome浏览器版本41.0.2272.89 m
我试图使我的websocket工作,但是由于某种原因,当我尝试访问套接字时,我得到了404(镀铬)。
WebSocket connection to 'ws://localhost:8080/InfiniteCloud/WebSocketExchange' failed: Error during WebSocket handshake: Unexpected response code: 404
当我尝试打开连接时发生错误。我从这个论坛上查询了很多以前的问题,但是没有一个起作用。这是我的服务器端代码:
package websocket;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.json.simple.JSONObject;
@ServerEndpoint( value = "/ClientDataExchange")
public class WebSocketExchange {
static Set<Session> _users = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void handleOpen(Session userSession){
_users.add(userSession);
}
@OnMessage
public void handleMessage(String message, Session userSession){
try{
if(userSession.getUserProperties().get("username") == null){
userSession.getUserProperties().put("username", message);
userSession.getBasicRemote().sendText( newUserJSONResponse(message) );
}
System.out.println("Message: " + message);
}catch(Exception e){
e.printStackTrace();
}
}
@OnClose
public void handleClose(Session userSession){
_users.remove(userSession);
}
public String newUserJSONResponse(String username){
JSONObject j = new JSONObject();
j.put("ICmessage", "You are now connected as: " + username);
return j.toJSONString();
}
}
客户端代码:
var websocket = null;
function sendMessage(){
websocket.send("Justin");
}
function testWebSocket(){
var url = "ws://" + document.location.host + document.location.pathname + "WebSocketExchange";
websocket = new WebSocket(url);
websocket.onopen = function(){
console.log("Connected to: " + url);
}
websocket.onmessage = function processMessage(message){
var jsonData = JSON.parse(message.data);
if(jsonData.message != null){
console.log(jsonData.message);
}else{
console.log("Empty message...");
}
}
websocket.onclose = function(){
console.log("Closing connection to: " + url);
}
}
最佳答案
您的路径似乎不匹配。在服务器上@ServerEndpoint( value = "/ClientDataExchange")
在客户身上
var url = "ws://" + document.location.host + document.location.pathname + "WebSocketExchange";