Spring boot webSocket
前几天学习了websocket 和Spring boot的结合 这里简单的做了记录,
后台工作
新建一个maven工程
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daijianweigroupId>
<artifactId>bootscoketartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<name>bootscoketname>
<description>Demo project for Spring Bootdescription>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.2.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>webjars-locator-coreartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>sockjs-clientartifactId>
<version>1.0.2version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>stomp-websocketartifactId>
<version>2.3.3version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.7version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
复制代码
新建websocket的配置类
WebSocketConfig 配置类
package com.daijianwei.bootscoket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
//通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样。
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.enableSimpleBroker("/topic"); //注册一个Stomp 协议的endpoint,并指定 SockJS协议。
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//配置消息代理(message broker)
registry.addEndpoint("/gs-guide-websocket").withSockJS();//广播式应配置一个/topic 消息代理
}
}
复制代码
创建一个消息的接受类
package com.daijianwei.bootscoket.bean;
public class HelloMessage {
private String name;
public HelloMessage(){
}
public HelloMessage(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
创建一个消息返回类
package com.daijianwei.bootscoket.bean;
public class Greeting {
private String content;
public Greeting(){}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
复制代码
控制器代码
package com.daijianwei.bootscoket.controller;
import com.daijianwei.bootscoket.bean.Greeting;
import com.daijianwei.bootscoket.bean.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
@Controller
public class GreetingController {
@MessageMapping("/hello")//浏览器发送请求通过@messageMapping 映射/hello 这个地址。
@SendTo("/topic/greetings")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
public Greeting greeting(HelloMessage message) throws InterruptedException {
Thread.sleep(1000);
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
复制代码
实现前台
添加脚本
在resources地下添加app.js 和main.css 文件
app.js
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('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/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("/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("" + message + " ");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
复制代码
main.css 文件
body {
background-color: #f5f5f5;
}
#main-content {
max-width: 940px;
padding: 2em 3em;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
复制代码
再添加一个index.html文件
<html>
<head>
<title>Hello WebSockettitle>
<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">Connectbutton>
<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">Sendbutton>
form>
div>
div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetingsth>
tr>
thead>
<tbody id="greetings">
tbody>
table>
div>
div>
div>
body>
html>
复制代码
Spring boot 启动类
package com.daijianwei.bootscoket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootscoketApplication {
public static void main(String[] args) {
SpringApplication.run(BootscoketApplication.class, args);
}
}
复制代码
启动程序 访问 http://localhost:8080/index.html
Spring boot webSocket
前几天学习了websocket 和Spring boot的结合 这里简单的做了记录,
后台工作
新建一个maven工程
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daijianweigroupId>
<artifactId>bootscoketartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<name>bootscoketname>
<description>Demo project for Spring Bootdescription>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.2.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>webjars-locator-coreartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>sockjs-clientartifactId>
<version>1.0.2version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>stomp-websocketartifactId>
<version>2.3.3version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.7version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
复制代码
新建websocket的配置类
WebSocketConfig 配置类
package com.daijianwei.bootscoket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
//通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样。
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.enableSimpleBroker("/topic"); //注册一个Stomp 协议的endpoint,并指定 SockJS协议。
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//配置消息代理(message broker)
registry.addEndpoint("/gs-guide-websocket").withSockJS();//广播式应配置一个/topic 消息代理
}
}
复制代码
创建一个消息的接受类
package com.daijianwei.bootscoket.bean;
public class HelloMessage {
private String name;
public HelloMessage(){
}
public HelloMessage(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
创建一个消息返回类
package com.daijianwei.bootscoket.bean;
public class Greeting {
private String content;
public Greeting(){}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
复制代码
控制器代码
package com.daijianwei.bootscoket.controller;
import com.daijianwei.bootscoket.bean.Greeting;
import com.daijianwei.bootscoket.bean.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
@Controller
public class GreetingController {
@MessageMapping("/hello")//浏览器发送请求通过@messageMapping 映射/hello 这个地址。
@SendTo("/topic/greetings")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
public Greeting greeting(HelloMessage message) throws InterruptedException {
Thread.sleep(1000);
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
复制代码
实现前台
添加脚本
在resources地下添加app.js 和main.css 文件
app.js
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('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/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("/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("" + message + " ");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
复制代码
main.css 文件
body {
background-color: #f5f5f5;
}
#main-content {
max-width: 940px;
padding: 2em 3em;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
复制代码
再添加一个index.html文件
<html>
<head>
<title>Hello WebSockettitle>
<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">Connectbutton>
<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">Sendbutton>
form>
div>
div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetingsth>
tr>
thead>
<tbody id="greetings">
tbody>
table>
div>
div>
div>
body>
html>
复制代码
Spring boot 启动类
package com.daijianwei.bootscoket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootscoketApplication {
public static void main(String[] args) {
SpringApplication.run(BootscoketApplication.class, args);
}
}
复制代码
启动程序 访问 http://localhost:8080/index.html
点击connect 链接websocket端口
同时打开另外一个窗口,访问http://localhost:8080/index.html
![](# Spring boot webSocket
前几天学习了websocket 和Spring boot的结合 这里简单的做了记录,
后台工作
新建一个maven工程
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daijianweigroupId>
<artifactId>bootscoketartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<name>bootscoketname>
<description>Demo project for Spring Bootdescription>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.2.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>webjars-locator-coreartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>sockjs-clientartifactId>
<version>1.0.2version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>stomp-websocketartifactId>
<version>2.3.3version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.7version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
复制代码
新建websocket的配置类
WebSocketConfig 配置类
package com.daijianwei.bootscoket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
//通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样。
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.enableSimpleBroker("/topic"); //注册一个Stomp 协议的endpoint,并指定 SockJS协议。
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//配置消息代理(message broker)
registry.addEndpoint("/gs-guide-websocket").withSockJS();//广播式应配置一个/topic 消息代理
}
}
复制代码
创建一个消息的接受类
package com.daijianwei.bootscoket.bean;
public class HelloMessage {
private String name;
public HelloMessage(){
}
public HelloMessage(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
创建一个消息返回类
package com.daijianwei.bootscoket.bean;
public class Greeting {
private String content;
public Greeting(){}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
复制代码
控制器代码
package com.daijianwei.bootscoket.controller;
import com.daijianwei.bootscoket.bean.Greeting;
import com.daijianwei.bootscoket.bean.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
@Controller
public class GreetingController {
@MessageMapping("/hello")//浏览器发送请求通过@messageMapping 映射/hello 这个地址。
@SendTo("/topic/greetings")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
public Greeting greeting(HelloMessage message) throws InterruptedException {
Thread.sleep(1000);
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
复制代码
实现前台
添加脚本
在resources地下添加app.js 和main.css 文件
app.js
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('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/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("/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("" + message + " ");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
复制代码
main.css 文件
body {
background-color: #f5f5f5;
}
#main-content {
max-width: 940px;
padding: 2em 3em;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
复制代码
再添加一个index.html文件
<html>
<head>
<title>Hello WebSockettitle>
<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">Connectbutton>
<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">Sendbutton>
form>
div>
div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetingsth>
tr>
thead>
<tbody id="greetings">
tbody>
table>
div>
div>
div>
body>
html>
复制代码
Spring boot 启动类
package com.daijianwei.bootscoket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootscoketApplication {
public static void main(String[] args) {
SpringApplication.run(BootscoketApplication.class, args);
}
}
复制代码
启动程序 访问 http://localhost:8080/index.html
Spring boot webSocket
前几天学习了websocket 和Spring boot的结合 这里简单的做了记录,
后台工作
新建一个maven工程
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daijianweigroupId>
<artifactId>bootscoketartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<name>bootscoketname>
<description>Demo project for Spring Bootdescription>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.2.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>webjars-locator-coreartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>sockjs-clientartifactId>
<version>1.0.2version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>stomp-websocketartifactId>
<version>2.3.3version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.7version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
复制代码
新建websocket的配置类
WebSocketConfig 配置类
package com.daijianwei.bootscoket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
//通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样。
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.enableSimpleBroker("/topic"); //注册一个Stomp 协议的endpoint,并指定 SockJS协议。
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//配置消息代理(message broker)
registry.addEndpoint("/gs-guide-websocket").withSockJS();//广播式应配置一个/topic 消息代理
}
}
复制代码
创建一个消息的接受类
package com.daijianwei.bootscoket.bean;
public class HelloMessage {
private String name;
public HelloMessage(){
}
public HelloMessage(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
创建一个消息返回类
package com.daijianwei.bootscoket.bean;
public class Greeting {
private String content;
public Greeting(){}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
复制代码
控制器代码
package com.daijianwei.bootscoket.controller;
import com.daijianwei.bootscoket.bean.Greeting;
import com.daijianwei.bootscoket.bean.HelloMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
@Controller
public class GreetingController {
@MessageMapping("/hello")//浏览器发送请求通过@messageMapping 映射/hello 这个地址。
@SendTo("/topic/greetings")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
public Greeting greeting(HelloMessage message) throws InterruptedException {
Thread.sleep(1000);
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
复制代码
实现前台
添加脚本
在resources地下添加app.js 和main.css 文件
app.js
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('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/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("/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("" + message + " ");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
复制代码
main.css 文件
body {
background-color: #f5f5f5;
}
#main-content {
max-width: 940px;
padding: 2em 3em;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
复制代码
再添加一个index.html文件
<html>
<head>
<title>Hello WebSockettitle>
<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">Connectbutton>
<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">Sendbutton>
form>
div>
div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetingsth>
tr>
thead>
<tbody id="greetings">
tbody>
table>
div>
div>
div>
body>
html>
复制代码
Spring boot 启动类
package com.daijianwei.bootscoket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootscoketApplication {
public static void main(String[] args) {
SpringApplication.run(BootscoketApplication.class, args);
}
}
复制代码
启动程序 访问 http://localhost:8080/index.html
点击connect 链接websocket端口
同时打开另外一个窗口,访问http://localhost:8080/index.html
在其中一个窗口输入文字
另一种方式(服务端广播式)
利用SimpMessagingTemplate
实现广播式推送
增加一个类
WebSocketController
package com.daijianwei.bootscoket.controller;
import com.daijianwei.bootscoket.bean.Greeting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@RequestMapping("/Welcome1")
@ResponseBody
public String say2() throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
// 每次向/topic/greetings 发送消息
simpMessagingTemplate.convertAndSend("/topic/greetings", new Greeting("daijianwei" + i));
System.out.println("----------------------send" + i);
}
return "is ok";
}
}
复制代码
同样在在浏览器的界面访问 http://localhost:8080/Welcome1
可以看到在两个界面的效果
参考文档
原spring boot +WebSocket 广播式(一) messaging-stomp-websocket SpringBoot中的WebSocket点对点发送消息