Java Spring 4 WebSocket 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20740956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring 4 WebSocket app
提问by Evgeni Dimitrov
I tried to run this example from the spring site: tutorialexcept the Spring Boot part.
我尝试从 spring 站点运行此示例: 除 Spring Boot 部分之外的教程。
Web.xml
网页.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.evgeni.websock.WebSocketConfig
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Java Config:
Java配置:
@Configuration
@ComponentScan(basePackages = {"com.evgeni.controller"})
@EnableWebSocketMessageBroker
@EnableWebMvc
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
public void configureClientInboundChannel(ChannelRegistration registration) {
// TODO Auto-generated method stub
}
public void configureClientOutboundChannel(ChannelRegistration registration) {
// TODO Auto-generated method stub
}
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
}
Controller:
控制器:
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
System.out.println(message.getName());
return new Greeting("Hello, " + message.getName() + "!");
}
}
index.jsp
索引.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="<c:url value='/js/sockjs-0.3.js'/>"></script>
<script src="<c:url value='/js/stomp.js'/>"></script>
<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("<c:url value='/hello'/>");
stompClient = Stomp.over(socket);
stompClient.connect('', '', function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe("<c:url value='/topic/greetings'/>", function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
stompClient.disconnect();
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("<c:url value='/app/hello'/>", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
Everithing is the same as the tutorial, except that the conf i loaded from the web.xml and 2-3 c:url in the jsp to add the root of the project.
除了我从web.xml加载的conf和jsp中的2-3个c:url添加项目的根目录外,一切都和教程一样。
When I click the connect and then send, in the browser console I get:
当我单击连接然后发送时,在浏览器控制台中我得到:
Opening Web Socket... stomp.js:122
Web Socket Opened... stomp.js:122
>>> CONNECT
login:
passcode:
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.js:122
<<< ERROR
message:Illegal header\c 'login\c'. A header must be of the form <name>\c<value>
content-length:0
stomp.js:122
>>> SEND
destination:/websock/app/hello
content-length:14
{"name":"asd"}
I think that th problm is in the connect function of Sock js
我认为问题出在 Sock js 的连接函数中
stompClient.connect('', '', function(frame) {...
I'm passing '' for login and passcode.
我正在传递 '' 用于登录和密码。
Edit:When I change the connect function to stompClient.connect('random', 'random',
the response in the console is:
编辑:当我将连接函数更改stompClient.connect('random', 'random',
为控制台中的响应时:
Opening Web Socket... stomp.js:122
Web Socket Opened... stomp.js:122
>>> CONNECT
login:asd
passcode:asd
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.js:122
<<< CONNECTED
heart-beat:0,0
version:1.1
stomp.js:122
connected to server undefined stomp.js:122
Connected: CONNECTED
version:1.1
heart-beat:0,0
(index):23
>>> SUBSCRIBE
id:sub-0
destination:/websock/topic/greetings
stomp.js:122
>>> SEND
destination:/websock/app/hello
content-length:14
{"name":"asd"}
but the message is not delivered to the controller.
但消息不会传递给控制器。
采纳答案by Evgeni Dimitrov
The mistake was wrong controller mapping. I have:
错误是错误的控制器映射。我有:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception
and in the jsp:
在jsp中:
stompClient.subscribe("<c:url value='/topic/greetings'/>", function(greeting){...
and
和
stompClient.send("<c:url value='/app/hello'/>", {}, JSON.stringify({ 'name': name }));
The right ones are:
正确的是:
stompClient.subscribe('/topic/greetings', function(greeting){...
stompClient.send('/app/hello', {}, JSON.stringify({ 'name': name }));
The c:url adds the root of the project, when I removed it the app worked. However c:url(the root) is rquired when create new socket with SockJs here:
c:url 添加了项目的根目录,当我删除它时,应用程序就可以工作了。但是,在此处使用 SockJs 创建新套接字时需要 c:url(the root):
var socket = new SockJS("<c:url value='/hello'/>");
回答by Adrian Ber
Also if you want not to pass login/password to server (as you might rely on Spring security) then you shouldn't use
此外,如果您不想将登录名/密码传递给服务器(因为您可能依赖 Spring 安全性),那么您不应该使用
stompClient.connect('', '', function(frame) {
but instead
但反而
stompClient.connect({}, function(frame) {
Take a look here: https://github.com/spring-guides/gs-messaging-stomp-websocket/issues/10
看看这里:https: //github.com/spring-guides/gs-messaging-stomp-websocket/issues/10