Skip to content

Commit

Permalink
Sample Implementation of Websocket Implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
SpielmannCode committed Sep 22, 2020
1 parent 94e8e2c commit 036f324
Show file tree
Hide file tree
Showing 9 changed files with 227 additions and 1 deletion.
1 change: 0 additions & 1 deletion README.md

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.idetix.hostbackend.Controller;

import com.idetix.hostbackend.Messages.Greeting;
import com.idetix.hostbackend.Messages.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendToUser("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception{
Thread.sleep(1000);
return new Greeting("Hello, "+ message.getName() + "!");
}

// @MessageMapping("/hello")
// @SendTo("/topic/greetings")
// public Greeting greeting(HelloMessage message) throws Exception{
// Thread.sleep(1000);
// return new Greeting("Hello, "+ message.getName() + "!");
// }


}
15 changes: 15 additions & 0 deletions src/main/java/com/idetix/hostbackend/HostbackendApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.idetix.hostbackend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class HostbackendApplication {

public static void main(String[] args) {
SpringApplication.run(HostbackendApplication.class, args);
}

}
13 changes: 13 additions & 0 deletions src/main/java/com/idetix/hostbackend/Messages/Greeting.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.idetix.hostbackend.Messages;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Greeting {
private String content;

}
13 changes: 13 additions & 0 deletions src/main/java/com/idetix/hostbackend/Messages/HelloMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.idetix.hostbackend.Messages;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class HelloMessage {

private String name;
}
51 changes: 51 additions & 0 deletions src/main/java/com/idetix/hostbackend/WebSocketBrokerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.idetix.hostbackend;



import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer {

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

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/host-backend")
.setHandshakeHandler(new DefaultHandshakeHandler(){
public boolean beforeHandshake(
ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map attributes) throws Exception{

if (request instanceof ServletServerHttpRequest){
ServletServerHttpRequest servletRequest
= (ServletServerHttpRequest) request;
HttpSession session = servletRequest
.getServletRequest().getSession();
attributes.put("sessionId", session.getId());
}
return true;
}
}).withSockJS();
}
}
50 changes: 50 additions & 0 deletions src/main/resources/static/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
var stompClient = null;

function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}

function connect() {
var socket = new SockJS('/host-backend');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}

function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}

function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}

function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
53 changes: 53 additions & 0 deletions src/main/resources/static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/main.css" rel="stylesheet">
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/app.js"></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 id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="name">What is your name?</label>
<input type="text" id="name" class="form-control" placeholder="Your name here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.idetix.hostbackend;

class HostbackendApplicationTests {

}

0 comments on commit 036f324

Please sign in to comment.