Skip to content

Commit 3896065

Browse files
committed
Add Spring WebSocket example
2 parents fe22d59 + 5fb75f5 commit 3896065

9 files changed

Lines changed: 3053 additions & 1 deletion

File tree

‎spring-mvc-java/pom.xml‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,28 @@
1717
<artifactId>spring-webmvc</artifactId>
1818
<version>${org.springframework.version}</version>
1919
</dependency>
20+
<dependency>
21+
<groupId>org.springframework</groupId>
22+
<artifactId>spring-websocket</artifactId>
23+
<version>${org.springframework.version}</version>
24+
</dependency>
25+
<dependency>
26+
<groupId>org.springframework</groupId>
27+
<artifactId>spring-messaging</artifactId>
28+
<version>${org.springframework.version}</version>
29+
</dependency>
30+
<!-- Jackson -->
31+
<dependency>
32+
<groupId>com.fasterxml.jackson.core</groupId>
33+
<artifactId>jackson-core</artifactId>
34+
<version>2.7.3</version>
35+
</dependency>
36+
<dependency>
37+
<groupId>com.fasterxml.jackson.core</groupId>
38+
<artifactId>jackson-databind</artifactId>
39+
<version>2.7.3</version>
40+
</dependency>
41+
2042
<!-- web -->
2143
<dependency>
2244
<groupId>javax.servlet</groupId>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.model;
2+
3+
public class Message {
4+
5+
private String from;
6+
private String text;
7+
8+
public String getText() {
9+
return text;
10+
}
11+
12+
public String getFrom() {
13+
return from;
14+
}
15+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.model;
2+
3+
public class OutputMessage {
4+
5+
private String from;
6+
private String text;
7+
private String time;
8+
9+
public OutputMessage(final String from, final String text, final String time) {
10+
11+
this.from = from;
12+
this.text = text;
13+
this.time = time;
14+
}
15+
16+
public String getText() {
17+
return text;
18+
}
19+
20+
public String getTime() {
21+
return time;
22+
}
23+
24+
public String getFrom() {
25+
return from;
26+
}
27+
}

‎spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
public class MainWebAppInitializer implements WebApplicationInitializer {
1616

17-
private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp";
17+
private static final String TMP_FOLDER = "/tmp";
1818
private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB
1919

2020
/**
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.spring.web.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
5+
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
6+
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
7+
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
8+
9+
@Configuration
10+
@EnableWebSocketMessageBroker
11+
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
12+
13+
@Override
14+
public void configureMessageBroker(final MessageBrokerRegistry config) {
15+
config.enableSimpleBroker("/topic");
16+
config.setApplicationDestinationPrefixes("/app");
17+
}
18+
19+
@Override
20+
public void registerStompEndpoints(final StompEndpointRegistry registry) {
21+
registry.addEndpoint("/chat").withSockJS();
22+
}
23+
24+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.web.controller;
2+
3+
import com.baeldung.model.Message;
4+
import com.baeldung.model.OutputMessage;
5+
import org.springframework.messaging.handler.annotation.MessageMapping;
6+
import org.springframework.messaging.handler.annotation.SendTo;
7+
import org.springframework.stereotype.Controller;
8+
9+
import java.text.SimpleDateFormat;
10+
import java.util.Date;
11+
12+
@Controller
13+
public class ChatController {
14+
15+
@MessageMapping("/chat")
16+
@SendTo("/topic/messages")
17+
public OutputMessage send(final Message message) throws Exception {
18+
19+
final String time = new SimpleDateFormat("HH:mm").format(new Date());
20+
return new OutputMessage(message.getFrom(), message.getText(), time);
21+
}
22+
23+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<html>
2+
<head>
3+
<title>Chat WebSocket</title>
4+
5+
<script src="./js/sockjs-0.3.4.js"></script>
6+
<script src="./js/stomp.js"></script>
7+
8+
<script type="text/javascript">
9+
10+
var stompClient = null;
11+
12+
function setConnected(connected) {
13+
14+
document.getElementById('connect').disabled = connected;
15+
document.getElementById('disconnect').disabled = !connected;
16+
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
17+
document.getElementById('response').innerHTML = '';
18+
}
19+
20+
function connect() {
21+
22+
var socket = new SockJS('/spring-mvc-java/chat');
23+
stompClient = Stomp.over(socket);
24+
25+
stompClient.connect({}, function(frame) {
26+
27+
setConnected(true);
28+
console.log('Connected: ' + frame);
29+
stompClient.subscribe('/topic/messages', function(messageOutput) {
30+
31+
showMessageOutput(JSON.parse(messageOutput.body));
32+
});
33+
});
34+
}
35+
36+
function disconnect() {
37+
38+
if(stompClient != null) {
39+
stompClient.disconnect();
40+
}
41+
42+
setConnected(false);
43+
console.log("Disconnected");
44+
}
45+
46+
function sendMessage() {
47+
48+
var from = document.getElementById('from').value;
49+
var text = document.getElementById('text').value;
50+
stompClient.send("/app/chat", {}, JSON.stringify({'from':from, 'text':text}));
51+
}
52+
53+
function showMessageOutput(messageOutput) {
54+
55+
var response = document.getElementById('response');
56+
var p = document.createElement('p');
57+
p.style.wordWrap = 'break-word';
58+
p.appendChild(document.createTextNode(messageOutput.from + ": " + messageOutput.text + " (" + messageOutput.time + ")"));
59+
response.appendChild(p);
60+
}
61+
62+
</script>
63+
64+
</head>
65+
66+
<body onload="disconnect()">
67+
68+
<div>
69+
70+
71+
<div>
72+
<input type="text" id="from" placeholder="Choose a nickname"/>
73+
</div>
74+
<br />
75+
<div>
76+
<button id="connect" onclick="connect();">Connect</button>
77+
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
78+
</div>
79+
<br />
80+
<div id="conversationDiv">
81+
<input type="text" id="text" placeholder="Write a message..."/>
82+
<button id="sendMessage" onclick="sendMessage();">Send</button>
83+
<p id="response"></p>
84+
</div>
85+
</div>
86+
87+
</body>
88+
</html>

0 commit comments

Comments
 (0)