java:springboot 整理webSocket

1、配置WebSocketConfig 类


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


@Configuration
@EnableWebSocket
public class WebSocketConfig {

    //如果需要引用service
    // @Autowired
    // public void socketAppTokenService(AppTokenService appTokenService) {
    //    WebSocketUtil.appTokenService = appTokenService;
    // }


    /**
     * 服务器节点
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

2、编写WebSocketUtil

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@ServerEndpoint("/ws")
@Component
public class WebSocketUtil {

    private static int onlineCount = 0;//在线人数
    private static CopyOnWriteArrayList<WebSocketUtil> webSocketSet = new CopyOnWriteArrayList<WebSocketUtil>();//在线用户集合
    private Session session;//与某个客户端的连接会话
    private String currentUser;
	
	//如果需要引用service
    //public static AppTokenService appTokenService;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        allCurrentOnline();
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        allCurrentOnline();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
        for (WebSocketUtil item : webSocketSet) {
            try {
                 //编写业务
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误!");
        throwable.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 获取当前所有在线用户名
     */
    public static void allCurrentOnline() {
        for (WebSocketUtil item : webSocketSet) {
            System.out.println(item.currentUser);
        }
    }

    /**
     * 发送给指定用户
     */
    public static void sendMessageTo(String message, String token) throws IOException {
        for (WebSocketUtil item : webSocketSet) {
            if (item.currentUser.equals(token)) {
                System.out.println("token:" + message);
                item.session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        System.out.println(message);
        for (WebSocketUtil item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

3、

@Slf4j
@RestController
public class WebSocketController {

    //给指定用户发
    @LoginIgnore
    @GetMapping("/send/{token}/{message}")
    public R sendMessage(@PathVariable("message") String message, @PathVariable("token") String token) throws IOException {
    WebSocketUtil.sendMessageTo(message,token)
        return R.ok();
    }


}

4、HTML测试

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Netty-Websocket</title>
    <script type="text/javascript">
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
        	//换成你的地址
            socket = new WebSocket("ws://127.0.0.1:9331/ws");
            socket.onmessage = function (event) {
                var ta = document.getElementById('responseText');
                let resData = JSON.parse(event.data);
                console.log(resData);
                ta.value += "消息: " + resData.proxy + "\t\t消息: " + resData.data + "\r\n";
            };
            socket.onopen = function (event) {
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。连接  \r\n";
            };
            socket.onclose = function (event) {
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。关闭 \r\n";
            };
        } else {
            alert("您的浏览器不支持WebSocket协议!");
        }

        function send(proxy,token,data) {
            if (!window.WebSocket) {
                return;
            }
            let param={
				proxy: proxy,
                token: token,
                data: data
            }
            if (socket.readyState == WebSocket.OPEN) {
                let resData = JSON.stringify(param);
                console.log(resData);
                socket.send(resData);
            } else {
                alert("WebSocket 连接没有建立成功!");
            }

        }

    </script>
</head>
<body>
<form onSubmit="return false;">
    <div>
        <label>proxy</label><input type="text" name="proxy" value="${proxy!!}"/> <br/>
		 <label>token</label><input type="text" name="token" value="${token!!}"/> <br/>
        <label>data</label><input type="text" name="data" value="这里输入数据"/> <br/>
        <br/> <input type="button" value="发送ws消息"
                     onClick="send(this.form.proxy.value, this.form.token.value,this.form.data.value)"/>
    </div>
    <hr color="black"/>
    <h3>服务端返回的应答消息</h3>
    <textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
</form>
</body>
</html> 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行人已

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值