您的位置:首页 > 财经 > 产业 > 百度地图导航手机版免费下载_重庆机械加工网_友情连接出售_2020站群seo系统

百度地图导航手机版免费下载_重庆机械加工网_友情连接出售_2020站群seo系统

2024/10/5 16:27:00 来源:https://blog.csdn.net/qq_44543774/article/details/142626367  浏览:    关键词:百度地图导航手机版免费下载_重庆机械加工网_友情连接出售_2020站群seo系统
百度地图导航手机版免费下载_重庆机械加工网_友情连接出售_2020站群seo系统

pom

:

        <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.53</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
<!--            <version>1.3.5.RELEASE</version>--></dependency>

前端页面1

<!DOCTYPE HTML>
<html>
<head><title>My WebSocket</title>
</head><body>
Welcome<br/>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body><script type="text/javascript">var websocket = null;//判断当前浏览器是否支持WebSocketif('WebSocket' in window){websocket = new WebSocket("ws://localhost:8080/websocket/1");}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(event){setMessageInnerHTML("open");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);//console.log(JSON.parse(event.data))}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//关闭连接function closeWebSocket(){websocket.close();}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}
</script>
</html>

前端页面2:

<!DOCTYPE HTML>
<html>
<head><title>My WebSocket</title>
</head><body>
Welcome<br/>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body><script type="text/javascript">var websocket = null;//判断当前浏览器是否支持WebSocketif('WebSocket' in window){websocket = new WebSocket("ws://localhost:8080/websocket/2");}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(event){setMessageInnerHTML("open");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);//console.log(JSON.parse(event.data))}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//关闭连接function closeWebSocket(){websocket.close();}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}
</script>
</html>

config配置类:

package com.example.demo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** @Author LHM* @Date 2024/9/27 11:25* @Description TODO*/
@Configuration
public class WebsocketAutoConfig {@Beanpublic ServerEndpointExporter endpointExporter() {return new ServerEndpointExporter();}
}

controller层:

package com.example.demo.controller;import lombok.extern.slf4j.Slf4j;
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;@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{id}")
public class WebsocketServerEndpoint {//在线连接数,应该把它设计成线程安全的private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。//虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。public static CopyOnWriteArraySet<WebsocketServerEndpoint> websocketServerSet= new CopyOnWriteArraySet<>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;//会话窗口的ID标识private String id = "";/*** 链接成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("id") String id) {log.info("onOpen >> 链接成功");this.session = session;//将当前websocket对象存入到Set集合中websocketServerSet.add(this);//在线人数+1addOnlineCount();log.info("有新窗口开始监听:" + id + ", 当前在线人数为:" + getOnlineCount());this.id = id;try {sendMessage("有新窗口开始监听:" + id + ", 当前在线人数为:" + getOnlineCount());} catch (Exception e) {log.error(e.toString());}}/*** 链接关闭调用的方法*/@OnClosepublic void onClose() {log.info("onClose >> 链接关闭");//移除当前Websocket对象websocketServerSet.remove(this);//在内线人数-1subOnLineCount();log.info("链接关闭,当前在线人数:" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message* @param session*/@OnMessagepublic void onMessage(String message, Session session) {log.info("接收到窗口:" + id + " 的信息:" + message);//发送信息for (WebsocketServerEndpoint websocketServerEndpoint : websocketServerSet) {try {websocketServerEndpoint.sendMessage("接收到窗口:" + id + " 的信息:" + message);} catch (Exception e) {e.printStackTrace();}}}@OnErrorpublic void onError(Session session, Throwable e) {e.printStackTrace();}/*** 推送消息** @param message*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}private void subOnLineCount() {WebsocketServerEndpoint.onlineCount--;}public static synchronized int getOnlineCount() {return onlineCount;}private void addOnlineCount() {WebsocketServerEndpoint.onlineCount++;}private void sendObject(Object object) throws IOException, EncodeException {this.session.getBasicRemote().sendObject(object);}
//   /** id为null时是群发
//     * @param map
//     * @param id
//     */public static void sendData(String id, Object map) {for (WebsocketServerEndpoint endpoint : websocketServerSet) {try {if (id == null) {endpoint.sendObject(map);} else if (endpoint.id.equals(id)) {endpoint.sendObject(map);}} catch (Exception e) {e.printStackTrace();continue;}}}}

发送数据:

package com.example.demo.demos;import com.example.demo.controller.WebsocketServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;import java.util.concurrent.CopyOnWriteArraySet;@Slf4j
@Configuration
@EnableScheduling
public class SendMessageToWeb {
//    @Autowired
//    WebsocketServerEndpoint websocketServerEndpoint;//每10秒发送一次@Scheduled(cron = "0/10 * * * * ?")public void sendTestMessage() {if(WebsocketServerEndpoint.websocketServerSet.size()>0){log.info("发送数据");try{//这里省略获取到需要发送数据data的逻辑  CopyOnWriteArraySet<WebsocketServerEndpoint> set =  WebsocketServerEndpoint.websocketServerSet;for (WebsocketServerEndpoint s:set) {s.sendMessage("zzz:" + System.currentTimeMillis());}}catch (Exception e){log.error(e.getMessage());}}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com