websocket创建连接和关闭连接简单实例

websocket创建连接和关闭连接简单实例懒得修改了 直接附上满足我需求的代码 java 文件 很多方法我没用到 package com example demo websocket import org springframew stereotype Component import javax websocket import javax websocket

大家好,我是讯享网,很高兴认识大家。

懒得修改了 直接附上满足我需求的代码:

java文件 很多方法我没用到

package com.example.demo.websocket; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import com.example.demo.controller.data_controller; @ServerEndpoint(value = "/websocket") @Component public class websocket_demo { 
    public static String rantime; public static int ranwendu; public static int ranshidu; public static int ranfengli; public static int ranpm; public static int ranrenkou; public static data_controller da=new data_controller(); public static int flag;//判断定时器是否开启的标志位 0为关闭 1开启 //统计在线人数 private static int onlineCount = 0; //用本地线程保存session private static ThreadLocal<Session> sessions = new ThreadLocal<Session>(); //保存所有连接上的session private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>(); public static synchronized int getOnlineCount() { 
    return onlineCount; } public static synchronized void addOnlineCount() { 
    onlineCount++; } public static synchronized void subOnlineCount() { 
    onlineCount--; } //连接 @OnOpen public static void onOpen(Session session) { 
    sessions.set(session); addOnlineCount(); sessionMap.put(session.getId(), session); flag=1; System.out.println("【" + session.getId() + "】连接上服务器======当前在线人数【" + getOnlineCount() + "】"); //连接上后给客户端一个消息 sendMsg(session, "连接服务器成功!"); timer(session);//定时器入口 } //关闭 @OnClose public static void onClose(Session session) { 
    subOnlineCount(); try { 
    if(session != null) session.close(); } catch (Exception e) { 
    e.printStackTrace(); } sessionMap.remove(session.getId()); System.out.println("【" + session.getId() + "】退出了连接======当前在线人数【" + getOnlineCount() + "】"); } //接收消息 客户端发送过来的消息 @OnMessage public void onMessage(String message, Session session) { 
    System.out.println("【" + session.getId() + "】客户端的发送消息======内容【" + message + "】"); String[] split = message.split(","); String sessionId = split[0]; Session ss = sessionMap.get(sessionId); if (ss != null) { 
    String msgTo = "【" + session.getId() + "】发送给【您】的消息:\n【" + split[1] + "】"; String msgMe = "【我】发送消息给【"+ss.getId()+"】:\n"+split[1]; sendMsg(ss, msgTo); sendMsg(session,msgMe); }else { 
    for (Session s : sessionMap.values()) { 
    if (!s.getId().equals(session.getId())) { 
    sendMsg(s, "【" + session.getId() + "】发送给【您】的广播消息:\n【" + message + "】"); } else { 
    sendMsg(session,"【我】发送广播消息给大家\n"+message); } } } } //异常 @OnError public void onError(Session session, Throwable throwable) { 
    System.out.println("发生异常!"); throwable.printStackTrace(); } //统一的发送消息方法 public static synchronized void sendMsg(Session session, String msg) { 
    try { 
    session.getBasicRemote().sendText(msg); } catch (IOException e) { 
    e.printStackTrace(); } } //产生随机数 动态更新excel表并重新读取 public static void addrandom(Session session){ 
    Random ra =new Random(); da.wendu=ra.nextInt(50)+0;da.shidu=ra.nextInt(100)+0;da.fengli=ra.nextInt(12)+0; da.pm=ra.nextInt(1000)+0;da.renkou=ra.nextInt(2000)+0; da.insertRows(); sendMsg(session,"1"); } public static void timer(Session session){ 
    new Thread(new Runnable() { 
    @Override public void run() { 
    while (flag==1&&session.isOpen()) { 
    addrandom(session); try { 
    Thread.sleep(15000); //15s } catch (InterruptedException e) { 
    // e.printStackTrace(); } } // onClose(session); 把这句话放出来就关闭了,用的方法比较笨 System.out.println(flag+"ttt"); } }).start(); } } 

讯享网

html里的部分js:


讯享网

讯享网 //监听是否开始产生随机数据 var startran=document.getElementById("randata"); startran.addEventListener('click', function(e) { 
    if (e.target.tagName.toLowerCase() != 'button') return; if (!startran) return; var rantext = startran.innerText; var s1 ; // if (socket.readyState === WebSocket.OPEN) { 
    // socket.close(); // } if (rantext == "开启随机数据") { 
    //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ 
    var websocket = new WebSocket("ws://localhost:8080/websocket"); //对应的是value值 } else{ 
    alert('Dont support websocket'); } //连接发生错误的回调方法 websocket.onerror = function(){ 
    alert("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ 
    alert("已开启,连接成功"); } //接收到消息的回调方法 websocket.onmessage = function(event){ 
    this.s1=websocket; trandata(); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ 
    websocket.close(); } //关闭连接 function closeWebSocket(){ 
    websocket.close(); } startran.innerText = "关闭随机数据"; } else{ 
    $.ajax({ 
    url: "/ranstatus", data:{ 
    }, dataType: "json",//数据格式 type: "post",//请求方式 async: false,//是否异步请求 success: function (data) { 
    //如果请求成功,返回数据。 alert("关闭!"); alert(data.status); }, error : function(data) { 
    alert("失败"+data.responseText); } }) alert("关闭成功!"); startran.innerText = "开启随机数据"; } }) 

部分controller:

@RequestMapping("/ranstatus") public Map<String,Object> ranstatus(){ 
    Map<String,Object> map = new HashMap<String, Object>(); socket.flag=0; map.put("status",200); return map; } 

websocket的config

讯享网package com.example.demo.websocket.config; 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(); } } 
小讯
上一篇 2025-03-28 12:01
下一篇 2025-04-11 19:05

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/117981.html