Skip to content

Commit

Permalink
Add Spring WebSocket example
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmorley committed May 12, 2016
2 parents fe22d59 + 5fb75f5 commit 3896065
Show file tree
Hide file tree
Showing 9 changed files with 3,053 additions and 1 deletion.
22 changes: 22 additions & 0 deletions spring-mvc-java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,28 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>

<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
Expand Down
15 changes: 15 additions & 0 deletions spring-mvc-java/src/main/java/com/baeldung/model/Message.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.baeldung.model;

public class Message {

private String from;
private String text;

public String getText() {
return text;
}

public String getFrom() {
return from;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.baeldung.model;

public class OutputMessage {

private String from;
private String text;
private String time;

public OutputMessage(final String from, final String text, final String time) {

this.from = from;
this.text = text;
this.time = time;
}

public String getText() {
return text;
}

public String getTime() {
return time;
}

public String getFrom() {
return from;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

public class MainWebAppInitializer implements WebApplicationInitializer {

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

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.baeldung.spring.web.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(final MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}

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

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.baeldung.web.controller;

import com.baeldung.model.Message;
import com.baeldung.model.OutputMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ChatController {

@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(final Message message) throws Exception {

final String time = new SimpleDateFormat("HH:mm").format(new Date());
return new OutputMessage(message.getFrom(), message.getText(), time);
}

}
88 changes: 88 additions & 0 deletions spring-mvc-java/src/main/webapp/resources/chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<html>
<head>
<title>Chat WebSocket</title>

<script src="./js/sockjs-0.3.4.js"></script>
<script src="./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('/spring-mvc-java/chat');
stompClient = Stomp.over(socket);

stompClient.connect({}, function(frame) {

setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function(messageOutput) {

showMessageOutput(JSON.parse(messageOutput.body));
});
});
}

function disconnect() {

if(stompClient != null) {
stompClient.disconnect();
}

setConnected(false);
console.log("Disconnected");
}

function sendMessage() {

var from = document.getElementById('from').value;
var text = document.getElementById('text').value;
stompClient.send("/app/chat", {}, JSON.stringify({'from':from, 'text':text}));
}

function showMessageOutput(messageOutput) {

var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(messageOutput.from + ": " + messageOutput.text + " (" + messageOutput.time + ")"));
response.appendChild(p);
}

</script>

</head>

<body onload="disconnect()">

<div>


<div>
<input type="text" id="from" placeholder="Choose a nickname"/>
</div>
<br />
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<br />
<div id="conversationDiv">
<input type="text" id="text" placeholder="Write a message..."/>
<button id="sendMessage" onclick="sendMessage();">Send</button>
<p id="response"></p>
</div>
</div>

</body>
</html>
Loading

0 comments on commit 3896065

Please sign in to comment.