전단 송신 브라우저 오브젝트의 통합을 달성 웹 소켓 springboot 수동 동작을 트리거 메시지를 전송

이러한 작업이이 표시하는 것입니다, 우리는 시스템 관리자가 우리가 프론트 엔드 캐시를 수행하는 방법의 코드를 업데이트 할 필요가 백그라운드에서 코드를 변경 브라우저 색인화, 내부 전면에 프로젝트 코드 캐시에 사용되는 버전을 사용하고자하기 시작했다 방법은 처리하는,하지만 당신은 필요를 사용할 때마다 서버에 압력을 너무 많이 코드를 업데이트 할 것인지 전에 네이티브 코드에 변화가 있는지 여부를 확인하려면 버전의 API 버전을 얻기 위해 호출 할 수 있습니다. 그런 다음 HTTP 느린 뉴스 만능 방법을 고려하고, 마지막으로이 단순히 이슈 웹 소켓 것을 이해, 미래는 또한 프로젝트의 라이브 채팅 기능을 확장하는 데 사용할 수 있습니다.

어떤 웹 소켓입니다

우리는 HTTP 프로토콜 먼저 브라우저가있는 서버로 요청을 보내는 것을 알고, 서버는이 요청에, 데이터가 브라우저로 전송됩니다 응답합니다. 서버 브라우저에 메시지를 전송해야하는 경우 HTML5 웹 소켓 브라우저 및 무제한 서버 사이의 전이중 (full-duplex) 통신을 설정할 수 있도록, 새로운 계약을 어떻게, 어느 주도권을 걸릴 수 있습니다 당사자는 상대방에게 메시지를 보냅니다.

SpringBoot - 웹 소켓 - 데모

프로젝트

  • springboot의 2.1.6.RELEASE

  • 스프링 부팅 스타터 웹 소켓

  • 이 프로젝트는 말초 브라우저를 보내는 것은 수동 조작을 트리거하는 메시지를 전송 실현하기 위해 통합 springboot의 웹 소켓 객체를 테스트하기 위해 주로이다.

Github에서 코드가 포털에 업로드 된 https://github.com/devmuyuer/SpringBoot-Websocket-Demo

코드 설명

  • 1. 새 프로젝트 spingboot 만들기

  • 2. 의존하는 웹 소켓 추가
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 3.WebSocketConfig
    열린 웹 소켓 지원
package com.example.socket;

/**
 * @author muyuer [email protected]
 * @version 1.0
 * @date 2019-07-22 18:16
 */

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

/**
 * 开启WebSocket支持
 * @author zhengkai
 */
@Configuration
public class WebSocketConfig {

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

}
  • 4.WebSocketServer
    웹 소켓 프로토콜 WS를 사용 WebSocketServer의 WS 여기서 동일한 프로토콜 콘트롤러
package com.example.socket;

import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * @author muyuer [email protected]
 * @version 1.0
 * @date 2019-07-22 18:17
 */
@ServerEndpoint("/web/socket/{sid}")
@Component
public class WebSocketServer {

    static Log log=LogFactory.get(WebSocketServer.class);
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收sid
      */
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(SocketMessage message) throws IOException {
        this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(SocketMessage message,@PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口"+sid+",推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
  • 5.WebSocketController
    프로젝트 (은 newMessage, CID)에 사용 된 시험 API를 호출 WebSocketServer.sendInfo 푸시 메시지
package com.example.socket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;

/**
 * @author muyuer [email protected]
 * @version 1.0
 * @date 2019-07-22 18:19
 */
@Controller
@RequestMapping("/web/socket")
public class WebSocketController {

    /**
     * 页面请求
     * @param cid
     * @return
     */
    @GetMapping("/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav=new ModelAndView("/socket");
        mav.addObject("cid", cid);
        return mav;
    }

    /**
     * 推送数据接口
     * @param cid
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping("/send/")
    public String pushToWeb(String cid,String message) {
        try {
            SocketMessage newMessage = new SocketMessage(message, new Date());
            WebSocketServer.sendInfo(newMessage,cid);
        } catch (IOException e) {
            e.printStackTrace();
            return cid+"#"+e.getMessage();
        }
        return cid;
    }
}

-6 전단 전화 번호

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8083/web/socket/20");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

테스트

  • 1.f9 프로젝트를 실행, 프로젝트 구성 파일을 수정할 수 8083 포트입니다
  • 2. 먼저, HTTP, 브라우저에 주소를 열 : // localhost를 : 8083 / 설정 연결을
  • 3. 액세스 주소에 http를 : // localhost를 : 8083 / 웹 / 소켓 / 20 // localhost를 :? 8083 / 웹 / 소켓 / CID = 20 & 메시지를 보낼 = 안녕 푸시 메시지는 연결 ID가 HTML "WS이다 확립 클라이언트 CID "아이디 (20)

참고 자료

추천

출처www.cnblogs.com/DevMuYuer/p/11236157.html