gpt4 book ai didi

javascript - WebSocket 连接到...失败 : Error during WebSocket handshake: Unexpected response code: 200

转载 作者:行者123 更新时间:2023-11-28 05:45:10 30 4
gpt4 key购买 nike

我正在尝试在 Chrome 浏览器和 Glassfish 4.1.1 服务器之间创建 websocket 连接。不幸的是,我收到 HTTP 200 消息而不是 101。

Chrome 开发工具日志:

"WebSocket connection to 'ws://DOMAIN_NAME:8080/serverendpointdemo/' failed: 
Error during WebSocket handshake: Unexpected response code: 200"

客户端代码:

var ws = new WebSocket ("ws://" + document.location.host + "/serverendpointdemo/");

服务器端代码:

package com.za.tutorial.websocket;

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

@ServerEndpoint("/home/USER_NAME/glassfish4/glassfish/domains/domain1/applications/serverendpointdemo")
public class ServerEndpointDemo {
@OnOpen
public void handleOpen() {
System.out.println("Client is now connected...");
}

@OnMessage
public String handleMessage (String message) {
return null;
}

@OnClose
public void handleClose () {
}

@OnError
public void handleError (Throwable t) {
t.printStackTrace();
}
}

最佳答案

服务器端:@ServerEndpoint(值 = "/ws")公共(public)类 WebSocketConfig {

private String message = "";
private String to = "";
private String from = "";
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

@OnOpen
public void onOpen(Session session, EndpointConfig econfig) throws IOException {
System.out.println("New Web Socket Connection created");
session.getBasicRemote().sendText("onOpen new socket connection");
}

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

@OnMessage
public void onMessage(String message, Session session) throws IOException {

}

客户端:

建立连接时,您应该指定上下文路径var ws = new WebSocket ("ws://"+ document.location.host +"/"+your-contextPathName+"/serverendpointdemo/");

http: ws://主机名:端口/contextpath/serverendpointhttps: wss://主机名:端口/contextpath/serverendpoint

例如:ws://document.location.host+"/WebsocketDemo/ws";

关于javascript - WebSocket 连接到...失败 : Error during WebSocket handshake: Unexpected response code: 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586405/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com