#java #javascript #spring #websocket
#java #javascript #spring #websocket
Вопрос:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
applicationContext.xml
<bean id="websocket" class="com.example.websocket.handler.WebsocketEndPoint" />
<websocket:handlers>
<websocket:mapping path="/websocket.ws" handler="websocket" />
<websocket:handshake-interceptors>
<bean class="com.example.websocket.HandshakeInterceptor" />
</websocket:handshake-interceptors>
</websocket:handlers>
HandshakeInterceptor.java
package com.example.websocket;
import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response,WebSocketHandler wsHandler,
Map<String,Object> attributes) throws Exception{
System.out.println("Before Handshake!");
return super.beforeHandshake(request,response,wsHandler,attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response,WebSocketHandler wsHandler,
Exception ex){
System.out.println("After HandShake!");
super.afterHandshake(request,response,wsHandler,ex);
}
}
WebsocketEndPoint.java
package com.example.websocket.handler;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class WebsocketEndPoint extends TextWebSocketHandler{
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception{
super.handleTextMessage(session, message);
System.out.println(message.getPayload());
TextMessage returnMessage =new TextMessage(message.getPayload() "received at server");
session.sendMessage(returnMessage);
}
}
Но я не могу подключиться к нему.
код javascript:
Chat.socket = new WebSocket('ws://localhost:80/Books/websocket.ws');
Это неправильный URL-адрес?
«Книги» — это название моего проекта в tomcat.
Вы знаете, что не так? Спасибо за любой ответ.
сервер работает нормально, но я получил сообщение об ошибке «Firefox не может подключиться к ws:// localhost/ Books/websocket.ws» [HTTP / 1.1 404 Не найдено 6 мс] с веб-консоли.
Комментарии:
1. Ваш кот находится на порту 80??? Попробуйте использовать новый WebSocket(‘ws:// localhost:8080/Books/websocket.ws’);
2. Опубликуйте полученную ошибку. Я, конечно, могу догадаться, что это стандартное «отказано в подключении», но никогда не знаешь наверняка.
3. @WornOutSoles из-за того, что я модифицировал порт tomcat, и я попробовал это.
4. @Gimby сервер в порядке, но я получил сообщение об ошибке «Firefox не может подключиться к ws:// localhost/ Books/websocket.ws» [HTTP / 1.1 404 Не найдено 6 мс] с веб-консоли.
5. Смотрите, это важная информация для кого-то, кто поможет вам ее исправить. Добавьте это в свой вопрос. Я могу рискнуть предположить, что ваш веб-сокет подключен к SSL, и в этом случае URL-адрес — wss://