1

Столкнулся с проблемой, что websocket сервер не открывается по ссылке ws://localhost:8080. Расширение на хром Simple WebSocket Client не видит таких websocketсерверов. Код взял отсюда: https://www.javainuse.com/spring/boot-websocket Страница открывается если просто переходить по localhost, если ввожу http://localhost выдает ошибку: Can "Upgrade" only to "WebSocket". В чем может быть проблема? Код application:

    package primer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Код SocketTextHandler:

package primer;

import java.io.IOException;

import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class SocketTextHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws InterruptedException, IOException {

        String payload = message.getPayload();
        JSONObject jsonObject = new JSONObject(payload);
        session.sendMessage(new TextMessage("Hi " + jsonObject.get("user") + " how may we help you?"));
    }

}

Код конфига:

package primer;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new SocketTextHandler(), "/user");
    }

}

Код app.js :

var ws;
function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
}

function connect() {
    ws = new WebSocket('ws://localhost:8080/user');
    ws.onmessage = function(data) {
        helloWorld(data.data);
    }
    setConnected(true);
}

function disconnect() {
    if (ws != null) {
        ws.close();
    }
    setConnected(false);
    console.log("Websocket is in disconnected state");
}

function sendData() {
    var data = JSON.stringify({
        'user' : $("#user").val()
    })
    ws.send(data);
}

function helloWorld(message) {
    $("#helloworldmessage").append("<tr><td> " + message + "</td></tr>");
}

$(function() {
    $("form").on('submit', function(e) {
        e.preventDefault();
    });
    $("#connect").click(function() {
        connect();
    });
    $("#disconnect").click(function() {
        disconnect();
    });
    $("#send").click(function() {
        sendData();
    });
});

В консоли после запуска пишет: 2022-11-09 11:01:56.454 INFO 16028 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) Почему в скобках http?

Запрос прошёл, но плагин все равно не находит такой страницы с ws

1
  • Может неточности в сервере? Кусок кода сервера хотя-бы обрисуйте 9 ноя 2022 в 5:53

1 ответ 1

0

Все заработало когда добавил к конфигу setAllowedOrigins("*");

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

       public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
             registry.addHandler(new SocketTextHandler(), "/user").setAllowedOrigins("*");
       }

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.