V
V
Vladimir Abdullaev2020-05-26 16:59:13
JavaScript
Vladimir Abdullaev, 2020-05-26 16:59:13

Why is there no websocket connection between browser and server?

Hello! Learning Java programming during self-isolation. I got to the point of creating my own little portfolio application, namely a chat. Wrote the server side and the client side. The first version was written in servlets with a server and Jetty websockets. The second part, in which the problem arose, was already written using the Spring framework. The essence of the problem lies in the fact that the client does not establish a connection via BC with the server. Unfortunately, so far, searching for the error and reading the Internet has not brought results. Perhaps the error is somewhere on the surface, and the lack of experience does not allow it to be detected. Thank you in advance for your time and possible response on this topic.

UDP 19:38
Corrected the connection via WS, but there was a problem with the delivery of the message to the client - there is no display in the desired block. The message is sent 100% - there is a display in the application console, but is not returned (or not displayed) to the clients...

The index.jsp file:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<!DOCTYPE HTML>
<html>
<head>
  <title>Главная</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <link rel="stylesheet" type="text/css" href="${contextPath}/resources/css/style.css">

    <script type="text/javascript">
        var stompClient = null;
        function setConnected(connected) {
            document.getElementById('connect').disabled = connected;
            document.getElementById('disconnect').disabled = !connected;
            document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
            document.getElementById('response').innerHTML = '';
        }
        function connect() {
            var socket = new SockJS('/chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/chating', function(message){
                    showGreeting(JSON.parse(chating.body).content);
                });
            });
        }
        function disconnect() {
            stompClient.disconnect();
            setConnected(false);
            console.log("Disconnected");
        }
        function sendMessage() {
            var message = document.getElementById('message').value;
            stompClient.send("/app/chat", {}, JSON.stringify(message));
        }
        function showMessage(message) {
            var resp = document.getElementById('messages');
            resp.value = resp.value + message.data + "\n";
        }
    </script>

</head>
<body>
<div class="center">
<div>
  <sec:authorize access="!isAuthenticated()">
    <a href="/login"><button>Войти</button></a>
    <a href="/registration"><button>Зарегистрироваться</button></a>
  </sec:authorize>
  <sec:authorize access="isAuthenticated()">
     <p>Привет, <b>${pageContext.request.userPrincipal.name}</b>!</p>
     <a href="/logout"><button>Выйти</button></a>
     <button id="connect" onclick="connect();">Соединение</button>
  </sec:authorize>
</div>
<div id="chatbox">
        <textarea id="messages" rows="20" cols="50" readonly="readonly"></textarea>
</div>
<sec:authorize access="isAuthenticated()">
    <form name="message" action="">
        <input name="usermsg" type="text" id="message" size="40"/>
        <input type="button" name="submitmsg" value="Send..." onclick="sendMessage();"/>
    </form>
</sec:authorize>
</div>
</body>
</html>


Controller:
package avi.com.vk.controller;


import avi.com.vk.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class MessageController {

    @MessageMapping("/chat")
    @SendTo("topic/chating")
    public Message message(String message) {
        return new Message(message);
    }
}


Configuration class:
package avi.com.vk.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
    }

}

Link to the entire repository:
https://github.com/memoryx3/ChatWS

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Abdullaev, 2020-05-26
@avi_sdk

I fixed the connection, everything works. Lost the necessary JS in the form:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

The connection is confirmed in the application console. Also, it is possible to send messages (they are displayed in the console). However, there is a problem with displaying them on the client side...Updated the question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question