五步教你springboot使用websocket

1.pom文件加入

		
			org.springframework.boot
			spring-boot-starter-websocket
			2.0.4.RELEASE
		

2.编写配置类,在你项目内新建一个包util,创建一个类WebSocketConfig
把下面代码复制

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();
    }

}

3.在controller包内创建新的类叫MyWebSocket复制下面代码即可

package com.hhy.cache.controller;

/**
 * @author hhy
 * @date 2020/8/13 - 9:44
 */
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
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;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

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


    private String name;
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入:"+"!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功,当前时间:" + new java.sql.Timestamp(System.currentTimeMillis()));
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("sname") String sname) {
        System.out.println("来自客户端"+name+"的消息:" + message);

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
                System.out.println("推送消息给:"+item.name+",消息是===》"+message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     * */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    /**
     * 服务端给客户端发送消息
     * @param message
     * @throws IOException
     */


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText("服务端回应消息:"+message+"------------->"+"服务器推送消息");


        //this.session.getAsyncRemote().sendText(message);
    }

    public void sendMessage1(String message){
        for (MyWebSocket webSocket: webSocketSet) {
            System.out.println("【websocket消息】广播消息, message={}"+message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }





    /**
     * 群发自定义消息
     * */
    public static void sendInfo(@PathParam("sname") String sname,String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if(sname==null) {
                    item.sendMessage(message);
                    System.out.println("推送消息给:"+item.name+",消息是===》"+message);
                }else if(item.name.equals(sname)){
                    item.sendMessage(message);
                    System.out.println("推送消息给:"+item.name+",消息是===》"+message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}

4.websocket前端页面编写,本页面和后端代码是我拿别人小项目改造了一下的,姓名可以不用输入,进入页面即可触发websocket




    My WebSocket
    



Welcome 

5.太复杂了,给源码你自己改造吧。
记得改项目配置文件的数据库密码和账户,这个源码是我改造了的,
sendMessage1(String message)这个才是群发消息,sendMessage(String message)是客户第一次进入发送消息,我indexcontroller设置了定时任务,不用你记得删了。
链接:https://pan.baidu.com/s/1XUPMS0oI8GCB5Kg5lBlEfA
提取码:8ygk

你可能感兴趣的:(五步教你springboot使用websocket)