websocket实现消息推送

1、创建一个springboot工程或者ssm工程

2、加入websocket的依赖包

<!-- Spring WebSocket -->
        <dependency>  
           <groupId>org.springframework</groupId>  
           <artifactId>spring-websocket</artifactId> 
           <version>${org.springframework.version}</version>   
        </dependency>  

3、创建socketServer.java文件用于实现对接

/**
 * 
 */
package com.test.socket;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * @author lyy
 *
 * 2021年1月13日-下午4:53:51
 */
@Component
@ServerEndpoint(value ="/start")
public class SocketServer {
    public Session session;
    //连接打开时执行
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.err.println("websocket连接成功!!!");       
    }
    //连接关闭时执行
    @OnClose
    public void onClose(Session session) {
        System.err.println("断开websocket连接!!!");
    }

    //收到消息时执行
    
    @OnMessage
    public void onMessage(String message,Session session) {
        System.out.println(message);
        for(int i=0;i<10;i++){
            send("我在自动推送第"+i+"条消息消息");
            try {
                TimeUnit.SECONDS.sleep(5); // 等待5秒
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

    /**
     * 发生错误时执行
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("【websocket发生错误】:" + error);
        error.printStackTrace();
    }
    public void send(String str){
        try {
            session.getBasicRemote().sendText(str);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

4、创建socketConfig.java文件

/**
 * 
 */
package com.test.socket;

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

/**
 * @author lyy
 *
 * 2021年1月13日-下午5:04:24
 */
@Configuration
public class ScoketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

5、创建前端html或jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
<html>    
    <head>    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
        <title>test</title>
        
        <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>    
    </head>    
        
    <body>  
       <h1>${test}</h1>
        <div>
            <input type="button" id="connection" value="连接" />
            <input type="button" id="close" value="关闭" />
            <input type="button" id="send" value="发送" />
        </div>
    </body>  
    <script type="text/javascript">
    var socket;
    if(typeof(WebSocket) == "undefined") {
        alert("您的浏览器不支持WebSocket");
    }else{
        $("#connection").click(function() {
            //实现化WebSocket对象,指定要连接的服务器地址与端口
            socket = new WebSocket("ws://127.0.0.1:8080/websocket/start");
            //打开事件
            socket.onopen = function() {
                alert("Socket 已打开");
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                alert(msg.data);
            };
            //关闭事件
            socket.onclose = function() {
                alert("Socket 已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                alert("socket出错");
            }
        });
        
        //发送消息
        $("#send").click(function() {
            socket.send("我是客户端!!!");
        });
        
        //关闭
        $("#close").click(function() {
            socket.close();
        });
    }

    
    
    </script>  
</html> 

最终结果:

 

posted @ 2021-01-14 16:24  过氧化氢  阅读(608)  评论(0编辑  收藏  举报