1. 初始化一个springboot 项目

项目框架如下:
image.png

2. 在pom.xml中添加依赖

  1. <!--主要核心依赖-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-websocket</artifactId>
  5. </dependency>
  6. <!--处理json的jar包, 可以换成自己的-->
  7. <dependency>
  8. <groupId>org.json</groupId>
  9. <artifactId>json</artifactId>
  10. <version>20171018</version>
  11. </dependency>

4. 创建SocketTextHandler, 为websocket提供服务

image.png

  1. import java.io.IOException;
  2. import org.json.JSONObject;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.socket.TextMessage;
  5. import org.springframework.web.socket.WebSocketSession;
  6. import org.springframework.web.socket.handler.TextWebSocketHandler;
  7. @Component
  8. public class SocketTextHandler extends TextWebSocketHandler {
  9. @Override
  10. public void handleTextMessage(WebSocketSession session, TextMessage message)
  11. throws InterruptedException, IOException {
  12. String payload = message.getPayload();
  13. JSONObject jsonObject = new JSONObject(payload);
  14. session.sendMessage(new TextMessage("Hi " +
  15. jsonObject.get("user") +
  16. " how may we help you?"));
  17. }
  18. }

5. 创建config类, 把第三步的controller类注册进来

image.png

  1. import com.javainuse.websocket.controller.SocketTextHandler;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  4. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  5. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  6. @Configuration
  7. @EnableWebSocket
  8. public class WebSocketConfig implements WebSocketConfigurer {
  9. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  10. registry.addHandler(new SocketTextHandler(), "/user");
  11. }
  12. }

注意添加@EnableWebSocket.

6. 添加前端页面

1, socket.html

使用boostrap3.0.3
https://bootstrapdocs.com/v3.0.3/docs/getting-started/
使用:jquery1.10.2
https://cdnjs.com/libraries/jquery/1.10.2

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>WebSocket Chat Application</title>
  5. <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
  6. <link href="/style.css" rel="stylesheet">
  7. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  8. <script src="/app.js"></script>
  9. </head>
  10. <body>
  11. <div id="main-content" class="container">
  12. <div class="row">
  13. <div class="col-md-8">
  14. <form class="form-inline">
  15. <div class="form-group">
  16. <label for="connect">Chat Application:</label>
  17. <button id="connect" type="button">Start New Chat</button>
  18. <button id="disconnect" type="button" disabled="disabled">End Chat
  19. </button>
  20. </div>
  21. </form>
  22. </div>
  23. </div>
  24. <div class="row">
  25. <div class="col-md-12">
  26. <table id="chat">
  27. <thead>
  28. <tr>
  29. <th>Welcome user. Please enter you name</th>
  30. </tr>
  31. </thead>
  32. <tbody id="helloworldmessage">
  33. </tbody>
  34. </table>
  35. </div>
  36. <div class="row">
  37. <div class="col-md-6">
  38. <form class="form-inline">
  39. <div class="form-group">
  40. <textarea id="user" placeholder="Write your message here..." required></textarea>
  41. </div>
  42. <button id="send" type="submit">Send</button>
  43. </form>
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48. </body>
  49. </html>

2, 添加js

  1. var ws;
  2. function setConnected(connected) {
  3. $("#connect").prop("disabled", connected);
  4. $("#disconnect").prop("disabled", !connected);
  5. }
  6. function connect() {
  7. ws = new WebSocket('ws://localhost:8080/user');
  8. ws.onmessage = function(data) {
  9. helloWorld(data.data);
  10. }
  11. setConnected(true);
  12. }
  13. function disconnect() {
  14. if (ws != null) {
  15. ws.close();
  16. }
  17. setConnected(false);
  18. console.log("Websocket is in disconnected state");
  19. }
  20. function sendData() {
  21. var data = JSON.stringify({
  22. 'user' : $("#user").val()
  23. })
  24. ws.send(data);
  25. }
  26. function helloWorld(message) {
  27. $("#helloworldmessage").append("<tr><td> " + message + "</td></tr>");
  28. }
  29. $(function() {
  30. $("form").on('submit', function(e) {
  31. e.preventDefault();
  32. });
  33. $("#connect").click(function() {
  34. connect();
  35. });
  36. $("#disconnect").click(function() {
  37. disconnect();
  38. });
  39. $("#send").click(function() {
  40. sendData();
  41. });
  42. });

3, 添加自定义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;
}

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
}

#page-wrapper {
  width: 650px;
  background: #FFF;
  padding: 1em;
  margin: 1em auto;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}

h1 {
    margin-top: 0;
}

#status {
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.open {
  color: green;
}

.closed {
  color: red;
}


ul {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 0.95rem;
}

ul li {
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #EEE;
}

ul li:first-child {
  border-top: 1px solid #EEE;
}

ul li span {
  display: inline-block;
  width: 90px;
  font-weight: bold;
  color: #999;
  font-size: 0.7rem;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.sent {
  background-color: #F7F7F7;
}

.received {}

#message-form {
  margin-top: 1.5rem;
}

textarea {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  border: 1px solid #D9D9D9;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
  min-height: 100px;
  margin-bottom: 1rem;
}

button {
  background: #86b32d;
  border-bottom: 1px solid #5d7d1f;
}

button[type="submit"] {
  background: #86b32d;
  border-bottom: 1px solid #5d7d1f;
}

button:hover {
  opacity: 0.75;
  cursor: pointer;
}

7. 项目运行截图

输入url: http://localhost:8080/socket.html
image.png

可以看到, js会访问/user 路径 - >ws = new WebSocket(‘ws://localhost:8080/user’);
后台服务器会调用SocketTextHandler处理来自/user的请求

项目代码: https://gitee.com/sky_memory/springboot-websocket.git

原文参考连接:https://www.javainuse.com/spring/boot-websocket