吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3129|回复: 3
收起左侧

[Java 转载] websocket思维导图

[复制链接]
lpc0828 发表于 2021-4-2 16:36
本帖最后由 lpc0828 于 2021-4-2 16:38 编辑

WebSocket.png
[Java] 纯文本查看 复制代码
/**
 * WebSocket服务端示例
 * @author Ray
 */
@Component
@Slf4j
@ServerEndpoint(value = "/ws/asset/{paraName}")
public class WebSocketServer {

    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。  
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        SessionSet.add(session);
        // 在线数加1
        int cnt = OnlineCount.incrementAndGet();
        log.info("有连接加入,当前连接数为:{}", cnt);
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭,当前连接数为:{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("来自客户端的消息:{}", message);
        SendMessage(session, "收到消息,消息内容:" + message);
    }

    /**
     * 出现错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
    }

    /**
     * 发送消息,实践表明,每次浏览器刷新,session会发生变化。
     *
     * @param session session
     * @param message 消息
     */
    private static void SendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId()));
    }

    /**
     * 群发消息
     *
     * @param message 消息
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : SessionSet) {
            if (session.isOpen()) {
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     *
     * @param sessionId sessionId
     * @param message   消息
     */
    public static void SendMessage(String sessionId, String message) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if (s.getId().equals(sessionId)) {
                session = s;
                break;
            }
        }
        if (session != null) {
            SendMessage(session, message);
        } else {
            log.warn("没有找到你指定ID的会话:{}", sessionId);
        }
    }

} 


[Java] 纯文本查看 复制代码
/**
 * WebSocket 核心配置类,项目启动时会自动启动,类似与ContextListener.
 * @author Ray
 */
@Configuration
public class WebSocketConfig implements ServerApplicationConfig{

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

    /**
     * 注解方式
     * 扫描src下所有类@ServerEndPoint注解的类。
     */
    @Override
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> arg0) {
        System.out.println("============="+arg0.size());
        //返回
        return arg0;
    }

    /**
     * 获取所有以接口方式配置的webSocket类。
     */
    @Override
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {
        return null;
    }

}


[Java] 纯文本查看 复制代码
/**
 * @ClassName api
 * @Author Ray
 * @Date 2021/3/31 15:09
 * @Description
 */
@RequestMapping("/api")
@Validated
@RestController
public class Controller {

    @GetMapping("/ws/sendOne")
    public void get(String message , String id) throws IOException {
        WebSocketServer.SendMessage(id,message);
    }

    @GetMapping("/ws/sendAll")
    public void get(String message) throws IOException {
        WebSocketServer.BroadCastInfo(message);
    }
}

[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>websocket测试</title>
    <style type="text/css">
        h3,h4{
            text-align:center;
        }
    </style>
</head>
<body>

<h3>WebSocket测试,在<span style="color:red">控制台</span>查看测试信息输出!</h3>
<h4>
    <br>
    http://localhost:8080/api/ws/sendOne?message=单发消息内容&id=none
    <br>
    http://localhost:8080/api/ws/sendAll?message=群发消息内容
</h4>

<h3>请输入要发送给服务器端的消息:</h3><br/>

<input id="text" type="text" />
<button>发送服务器消息</button>
<button>关闭连接</button>
<br>信息:<span id="message"></span>


<script type="text/javascript">
    let socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("遗憾:您的浏览器不支持WebSocket");
    } else {
        socket = new WebSocket("ws://localhost:8080/ws/asset/999");
        //连接打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            socket.send("消息发送测试(From Client)");
        };
        //收到消息事件
        socket.onmessage = function(msg) {
            document.getElementById('message').innerHTML += msg.data + '<br/>';
        };
        //连接关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
        }

        //窗口关闭时,关闭连接
        window.unload=function() {
            socket.close();
        };
    }

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

    //发送消息给服务器
    function sendToServer(){
        let message = document.getElementById('text').value;
        socket.send(message);
    }
</script>

</body>
</html>

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

每年工资两千五 发表于 2021-4-2 16:53
我最近也在看websocket    谢谢 你的导图了
传说中的死肥宅 发表于 2021-4-2 17:01
gbk38866 发表于 2022-7-28 15:05
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-24 11:54

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表