WebSocket Basics - Basic concepts of WebSocket VS Http & SpringBoot integrate WebSocket & vue front-end code and effect display

Preface

WebSocket is a protocol for full-duplex communication between a web browser and a server. It allows bidirectional communication over a single TCP connection without the need for multiple HTTP request-response loops. Compared with traditional HTTP requests, WebSocket provides lower latency and higher real-time performance.

This blog introduces the basic concepts of WebSocket, the difference and connection with http, and then introduces the integration of SpringBoot with WebSocket, as well as the Vue front-end code and effect display.

Insert image description here

lead out


1. The basic concept of WebSocket, the difference and connection with http;
2. Springboot integrates WebSocket;
3. Vue front-end code and effect display;

Use of WebSockets

Get to know websock

WebSocket is a protocol for full-duplex communication between a web browser and a server. It allows bidirectional communication over a single TCP connection without the need for multiple HTTP request-response loops. Compared with traditional HTTP requests, WebSocket provides lower latency and higher real-time performance.

The WebSocket protocol works by upgrading the connection during the HTTP handshake phase. Once a WebSocket connection is established, real-time communication can occur between the client and the server by sending messages. This two-way communication feature makes WebSocket very suitable for real-time chat, real-time data updates, multi-player games and other applications that require real-time performance.

The WebSocket protocol is based on the standard TCP protocol and can be used on modern web browsers and servers. It provides a more efficient and real-time communication method, allowing developers to build more interactive and real-time web applications.

WebSocket has the following characteristics:

  1. Two-way communication: WebSocket allows two-way communication between client and server, not just one-way request-response mode. This makes it easier to push live data and update it in real time.
  2. Real-time: WebSocket provides low-latency and high-real-time communication, allowing data to be transmitted and processed at a faster speed. Compared with traditional HTTP requests, WebSocket reduces additional overhead and latency.
  3. Less data transfer volume: WebSocket uses less data transfer volume because it uses binary data framing and compression technology to reduce the size of the data. This is very beneficial for mobile devices and environments with limited network bandwidth.
  4. Long connection: WebSocket can maintain a long-term connection state after establishing a connection without the need to frequently establish and close the connection. This reduces server load and network overhead.
  5. Cross-domain support: WebSocket supports cross-domain communication, allowing communication between different domain names or different ports. This provides convenience for building distributed systems and cross-domain applications.
  6. Extensibility: The WebSocket protocol is extensible and can be added to meet specific needs by adding custom protocol extensions.

WebSocket provides a more efficient, real-time, and reliable communication method, allowing developers to build more interactive and real-time Web applications.

Insert image description here

WebSocket and HTTP have the following differences and connections:

the difference:

  1. Connection method: HTTP is a stateless protocol based on the request-response model. Each request requires a new connection to be established. WebSocket is a long connection protocol. After a handshake, a persistent connection can be maintained between the client and the server to achieve two-way communication.
  2. Data transmission method: HTTP uses text format to transmit data, while WebSocket can transmit data using text or binary format.
  3. Communication efficiency: Because WebSocket uses long connections, it reduces the overhead of establishing and closing connections, as well as the repeated transmission of HTTP headers, so it is better than HTTP in terms of real-time performance and communication efficiency.

connect:

  1. Handshake process: The handshake process of WebSocket is based on HTTP. The client and server first perform an HTTP handshake and then upgrade to the WebSocket protocol.
  2. Use the same port: WebSocket and HTTP can share the same port. Because the handshake process of WebSocket is based on HTTP, communication can be carried out through HTTP port 80 or 443.
  3. Compatibility: The WebSocket protocol is based on the standard TCP protocol and can be used on modern web browsers and servers. Compared to HTTP, WebSocket is broader in terms of compatibility.

Insert image description here

springboot integrates websocket

Insert image description here

1. Import dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2. Configuration files and configuration classes

package com.tianju.webChat.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    
    
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
    
    
        return new ServerEndpointExporter();
    }
}

server:
  port: 10065


logging:
  level:
    com.tianju.socket: debug

3. Custom tool class

Insert image description here

package com.tianju.webChat.util;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 聊天室的工具类
 */
public class WebSocketUtil {
    
    
    //放所有参与聊天的用户标识
    public static final Map<String, Session> messageMap = new ConcurrentHashMap<>();

    /**
     *单个消息
     */
    public static void send(Session session,String message){
    
    
        if (session != null){
    
    
            final RemoteEndpoint.Basic basic = session.getBasicRemote();
            if (basic != null){
    
    
                try {
    
    
                    basic.sendText(message);
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 全体发消息
     */
    public static void sendAll(String message){
    
    
        messageMap.forEach((userName,session) -> send(session,message));
    }
}

4.controller layer

Insert image description here

package com.tianju.webChat.controller;


import com.tianju.webChat.util.WebSocketUtil;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")


public class WebChatController {
    
    
    @OnOpen
    public void openSession(@PathParam("userName") String userName, Session session){
    
    
        String message = "欢迎:"+userName +"加入群聊";
        WebSocketUtil.messageMap.put(userName,session);
        //给所有人发消息
        WebSocketUtil.sendAll(message);

    }
    @OnMessage
    public void onMessage(@PathParam("userName") String userName, String message){
    
    
        message = userName +":" +message;
        WebSocketUtil.sendAll(message);
    }


    @OnClose
    public void onClose(@PathParam("userName") String userName,Session session){
    
    
        WebSocketUtil.messageMap.remove(userName);
        WebSocketUtil.sendAll("用户:"+userName+"离开聊天室");
        try {
    
    
            session.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

5. Main startup class

Insert image description here

package com.tianju.webChat;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

@SpringBootApplication
@EnableWebSocket
public class WebChatApp {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(WebChatApp.class);
    }
}

vue front-end code

Insert image description here

<template>
  <div>

    <el-row>
      <el-col :span="6" :offset="3">
        <p style="font-">真心聊天室</p>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12" :offset="1"> <textarea id="textarea" disabled="disabled" cols="50" rows="10"></textarea></el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <span> 用户名:</span>
        <span> <el-input type="text" v-model="userName" /></span>
        <span> <el-button type="primary" @click="join">加入聊天室</el-button></span>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <span> 发消息:</span>
        <span> <el-input type="text" v-model="message" /></span>
        <span> <el-button type="success" @click="send">发送</el-button></span>
      </el-col>
    </el-row>


  </div>
</template>

<script>

export default {
    
    
  data() {
    
    
    return {
    
    
      url: 'ws://127.0.0.1:10065/WebSocketHandler/',
      ws: '',
      userName: '',
      message: ''
    }

  },
  methods: {
    
    
    join() {
    
    
      if (this.userName == "") {
    
    
        alert("请输入您的大名!")
      }
      this.ws = new WebSocket(this.url + this.userName);

      this.ws.onopen = function () {
    
    
        console.log("连接成功!")
      }

      this.ws.onmessage = function (result) {
    
    

        var textarea = document.getElementById("textarea");
        textarea.append(result.data + '\n');
        // 使textarea元素滚动到底部,显示最后一行文本
        textarea.scrollTop = textarea.scrollHeight;
      }

      this.ws.onclose = function () {
    
    
        var textarea = document.getElementById("textarea");
        textarea.append('用户:' + this.userName + '离开聊天室 \n');
        console.log("")
      }

    },
    send() {
    
    
      if (this.ws != null) {
    
    
        this.ws.send(this.message);
        this.message = "";
      }
    }
  }
}
</script>

<style scoped>
p {
    
    
  font-size: 20px;
  color: red;
}

.el-row {
    
    
  margin: 10px 5px;
}

span {
    
    
  float: left;
}</style>

Effect demonstration

Insert image description here

Multiple people can join the chat

Insert image description here


Summarize

1. The basic concept of WebSocket, the difference and connection with http;
2. Springboot integrates WebSocket;
3. Vue front-end code and effect display;

Guess you like

Origin blog.csdn.net/Pireley/article/details/133513554