SpringBoot+Redis实现分布式WebSocket

news2024/9/22 11:36:37

什么是分布式WebSocket?

是指在分布式系统架构中实现WebSocket的通信机制,它允许在不同的服务器节点之间共享和同步WebSocket会话状态,从而实现跨多个服务器的实时消息传递。

在分布式环境中实现WebSocket的挑战主要包括以下几点:

  1. 会话共享:在分布式系统中,用户的WebSocket连接可能与不同的服务器建立,这就要求系统能够在不同服务器间共享WebSocket会话信息,以便消息能够被正确地传递到所有相关的客户端。
  2. 负载均衡:使用负载均衡可以提高系统的可用性和伸缩性。但是,当WebSocket请求在服务器之间负载均衡时,需要确保客户端可以与正确的服务器建立连接,并且能够接收到所有的消息。
  3. 故障转移:在出现服务器故障时,系统需要能够将WebSocket会话无缝迁移到其他健康的服务器上,以保证服务的连续性。
  4. 一致性:确保所有用户在任何时候看到的都是一致的消息状态,这对于实时通信非常重要。

为了解决这些挑战,可以采取以下几种策略:

  1. 使用消息代理:通过引入一个中心化的消息代理(如RabbitMQ、Redis Pub/Sub等),可以让所有的服务器都连接到这个消息代理。当一个服务器需要发送消息时,它将消息发送到消息代理,然后由消息代理负责将消息分发到所有连接的客户端。这样可以确保消息的一致性和可靠性。
  2. 共享会话存储:使用一个共享的会话存储(如数据库或内存数据网格)来保存WebSocket会话的状态。这样,即使客户端最初连接到的服务器发生故障,其他服务器也可以接管会话并继续处理消息。
  3. 基于路由的负载均衡:使用智能负载均衡器(如Nginx、HAProxy等),它们可以根据特定的路由规则(如会话ID或用户ID)将WebSocket连接定向到特定的服务器。
  4. 服务发现:在微服务架构中,可以使用服务发现机制来动态地找到负责特定会话的服务器,并将消息路由到那里。
  5. WebSocket代理:使用专门的WebSocket代理服务器,它可以在多个后端服务器之间代理WebSocket连接,并确保消息的传递和会话的同步。
  6. 应用层协议:设计应用层协议来处理分布式WebSocket的复杂性,例如通过引入心跳机制来检测连接的健康状况,并通过预定的协议来同步会话状态。

总的来说,在实践中,可能需要结合多种策略来构建一个健壮的分布式WebSocket解决方案,以满足不同场景下的需求。此外,还需要考虑安全性、性能和可扩展性等因素,以确保系统的稳定性和可靠性。

温故而知新:单点WebSocket实现

SpringBoot2.0集成WebSocket,实现后台向前端推送信息_springboot集成websocket-CSDN博客icon-default.png?t=N7T8https://zhengkai.blog.csdn.net/article/details/80275084

简单版本:在Java中使用Redis实现WebSocket

要在Java中使用Redis实现WebSocket,你需要使用一个支持WebSocket的Java Web框架,如Spring Boot,以及一个支持Redis的Java库,如Jedis。以下是一个简单的示例:

添加依赖项到你的pom.xml文件

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

创建一个WebSocket配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
//by zhengkai.blog.csdn.net
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

    @Override
    public void configureMessageBroker(org.springframework.messaging.simp.config.MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(new RedisMessageListener());
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(jedisConnectionFactory());
        container.addMessageListener(messageListenerAdapter(), topic());
        return container;
    }

    @Bean
    public ChannelTopic topic() {
        return new ChannelTopic("websocket-topic");
    }
}

创建一个WebSocket消息监听器

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Component
public class RedisMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("Received message: " + message);
    }
}

发送消息到WebSocket客户端

在你的控制器中,你可以使用SimpMessagingTemplate来发送消息到WebSocket客户端:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @GetMapping("/send")
    public String sendMessage() {
        messagingTemplate.convertAndSend("/topic/websocket-topic", "Hello from Redis!");
        return "Message sent!";
    }
}

正式版本:用SpringBoot+Redis实现分布式WebSocket

 

  1. 将消息(<用户id消息内容>)统一推送到一个消息队列(RedisKafka等)的的topic,然后每个应用节点都订阅这个topic,在接收到WebSocket消息后取出这个消息的“消息接收者的用户ID/用户名”,然后再比对自身是否存在相应用户的连接,如果存在则推送消息,否则丢弃接收到的这个消息(这个消息接收者所在的应用节点会处理)
  2. 在用户建立WebSocket连接后,使用Redis缓存记录用户的WebSocket建立在哪个应用节点上,然后同样使用消息队列将消息推送到接收者所在的应用节点上面(实现上比方案一要复杂,但是网络流量会更低)

 

 1. 定义一个WebSocket Channel枚举类

public enum WebSocketChannelEnum {
    //测试使用的简易点对点聊天
    CHAT("CHAT", "测试使用的简易点对点聊天", "/topic/reply");
 
    WebSocketChannelEnum(String code, String description, String subscribeUrl) {
        this.code = code;
        this.description = description;
        this.subscribeUrl = subscribeUrl;
    }
 
    /**
     * 唯一CODE
     */
    private String code;
    /**
     * 描述
     */
    private String description;
    /**
     * WebSocket客户端订阅的URL
     */
    private String subscribeUrl;
 
    public String getCode() {
        return code;
    }
 
    public String getDescription() {
        return description;
    }
 
    public String getSubscribeUrl() {
        return subscribeUrl;
    }
 
    /**
     * 通过CODE查找枚举类
     */
    public static WebSocketChannelEnum fromCode(String code){
        if(StringUtils.isNoneBlank(code)){
            for(WebSocketChannelEnum channelEnum : values()){
                if(channelEnum.code.equals(code)){
                    return channelEnum;
                }
            }
        }
 
        return null;
    }
 
}

2. 配置基于Redis的消息队列

需要注意的是,在大中型正式项目中并不推荐使用Redis实现的消息队列,因为经过测试它并不是特别可靠,所以应该考虑使用KafkarabbitMQ等专业的消息队列中间件

@Configuration
@ConditionalOnClass({JedisCluster.class})
public class RedisConfig {
 
    @Value("${spring.redis.timeout}")
    private String timeOut;
 
    @Value("${spring.redis.cluster.nodes}")
    private String nodes;
 
    @Value("${spring.redis.cluster.max-redirects}")
    private int maxRedirects;
 
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
 
    @Value("${spring.redis.jedis.pool.max-wait}")
    private int maxWait;
 
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
 
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
 
    @Value("${spring.redis.message.topic-name}")
    private String topicName;
 
    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWait);
 
        return config;
    }
 
    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        RedisClusterConfiguration configuration = new RedisClusterConfiguration(Arrays.asList(nodes));
        configuration.setMaxRedirects(maxRedirects);
 
        return configuration;
    }
 
    /**
     * JedisConnectionFactory
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(RedisClusterConfiguration configuration,JedisPoolConfig jedisPoolConfig){
        return new JedisConnectionFactory(configuration,jedisPoolConfig);
    }
 
    /**
     * 使用Jackson序列化对象
     */
    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(){
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
 
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);
 
        return serializer;
    }
 
    /**
     * RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory, Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
 
        //字符串方式序列化KEY
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
 
        //JSON方式序列化VALUE
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
 
        redisTemplate.afterPropertiesSet();
 
        return redisTemplate;
    }
 
    /**
     * 消息监听器
     */
    @Bean
    MessageListenerAdapter messageListenerAdapter(MessageReceiver messageReceiver, Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer){
        //消息接收者以及对应的默认处理方法
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(messageReceiver, "receiveMessage");
        //消息的反序列化方式
        messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
 
        return messageListenerAdapter;
    }
 
    /**
     * message listener container
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory
            , MessageListenerAdapter messageListenerAdapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //添加消息监听器
        container.addMessageListener(messageListenerAdapter, new PatternTopic(topicName));
 
        return container;
    }
 
}

这里使用的配置:

spring:
  ...
  #redis
  redis:
      cluster:
        nodes: namenode22:6379,datanode23:6379,datanode24:6379
        max-redirects: 6
      timeout: 300000
      jedis:
        pool:
          max-active: 8
          max-wait: 100000
          max-idle: 8
          min-idle: 0
      #自定义的监听的TOPIC路径
      message:
        topic-name: topic-test

3. 定义一个Redis消息的处理者

@Component
public class MessageReceiver {
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
 
    @Autowired
    private SimpUserRegistry userRegistry;
 
    /**
     * 处理WebSocket消息
     */
    public void receiveMessage(RedisWebsocketMsg redisWebsocketMsg) {
        logger.info(MessageFormat.format("Received Message: {0}", redisWebsocketMsg));
        //1. 取出用户名并判断是否连接到当前应用节点的WebSocket
        SimpUser simpUser = userRegistry.getUser(redisWebsocketMsg.getReceiver());
 
        if(simpUser != null && StringUtils.isNoneBlank(simpUser.getName())){
            //2. 获取WebSocket客户端的订阅地址
            WebSocketChannelEnum channelEnum = WebSocketChannelEnum.fromCode(redisWebsocketMsg.getChannelCode());
 
            if(channelEnum != null){
                //3. 给WebSocket客户端发送消息
                messagingTemplate.convertAndSendToUser(redisWebsocketMsg.getReceiver(), channelEnum.getSubscribeUrl(), redisWebsocketMsg.getContent());
            }
        }
 
    }
}

4. 在Controller中发送WebSocket消息

@Controller
@RequestMapping(("/wsTemplate"))
public class RedisMessageController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    @Value("${spring.redis.message.topic-name}")
    private String topicName;
 
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
 
    @Autowired
    private SimpUserRegistry userRegistry;
 
    @Resource(name = "redisServiceImpl")
    private RedisService redisService;
 
    /**
     * 给指定用户发送WebSocket消息
     */
    @PostMapping("/sendToUser")
    @ResponseBody
    public String chat(HttpServletRequest request) {
        //消息接收者
        String receiver = request.getParameter("receiver");
        //消息内容
        String msg = request.getParameter("msg");
        HttpSession session = SpringContextUtils.getSession();
        User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
 
        HelloMessage resultData = new HelloMessage(MessageFormat.format("{0} say: {1}", loginUser.getUsername(), msg));
        this.sendToUser(loginUser.getUsername(), receiver, WebSocketChannelEnum.CHAT.getSubscribeUrl(), JsonUtils.toJson(resultData));
 
        return "ok";
    }
 
    /**
     * 给指定用户发送消息,并处理接收者不在线的情况
     * @param sender 消息发送者
     * @param receiver 消息接收者
     * @param destination 目的地
     * @param payload 消息正文
     */
    private void sendToUser(String sender, String receiver, String destination, String payload){
        SimpUser simpUser = userRegistry.getUser(receiver);
 
        //如果接收者存在,则发送消息
        if(simpUser != null && StringUtils.isNoneBlank(simpUser.getName())){
            messagingTemplate.convertAndSendToUser(receiver, destination, payload);
        }
        //如果接收者在线,则说明接收者连接了集群的其他节点,需要通知接收者连接的那个节点发送消息
        else if(redisService.isSetMember(Constants.REDIS_WEBSOCKET_USER_SET, receiver)){
            RedisWebsocketMsg<String> redisWebsocketMsg = new RedisWebsocketMsg<>(receiver, WebSocketChannelEnum.CHAT.getCode(), payload);
 
            redisService.convertAndSend(topicName, redisWebsocketMsg);
        }
        //否则将消息存储到redis,等用户上线后主动拉取未读消息
        else{
            //存储消息的Redis列表名
            String listKey = Constants.REDIS_UNREAD_MSG_PREFIX + receiver + ":" + destination;
            logger.info(MessageFormat.format("消息接收者{0}还未建立WebSocket连接,{1}发送的消息【{2}】将被存储到Redis的【{3}】列表中", receiver, sender, payload, listKey));
 
            //存储消息到Redis中
            redisService.addToListRight(listKey, ExpireEnum.UNREAD_MSG, payload);
        }
 
    }
 
 
    /**
     * 拉取指定监听路径的未读的WebSocket消息
     * @param destination 指定监听路径
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping("/pullUnreadMessage")
    @ResponseBody
    public Map<String, Object> pullUnreadMessage(String destination){
        Map<String, Object> result = new HashMap<>();
        try {
            HttpSession session = SpringContextUtils.getSession();
            //当前登录用户
            User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
 
            //存储消息的Redis列表名
            String listKey = Constants.REDIS_UNREAD_MSG_PREFIX + loginUser.getUsername() + ":" + destination;
            //从Redis中拉取所有未读消息
            List<Object> messageList = redisService.rangeList(listKey, 0, -1);
 
            result.put("code", "200");
            if(messageList !=null && messageList.size() > 0){
                //删除Redis中的这个未读消息列表
                redisService.delete(listKey);
                //将数据添加到返回集,供前台页面展示
                result.put("result", messageList);
            }
        }catch (Exception e){
            result.put("code", "500");
            result.put("msg", e.getMessage());
        }
 
        return result;
    }
 
}

5. WebSocket相关配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
    @Autowired
    private AuthHandshakeInterceptor authHandshakeInterceptor;
 
    @Autowired
    private MyHandshakeHandler myHandshakeHandler;
 
    @Autowired
    private MyChannelInterceptor myChannelInterceptor;
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat-websocket")
                .addInterceptors(authHandshakeInterceptor)
                .setHandshakeHandler(myHandshakeHandler)
                .withSockJS();
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //客户端需要把消息发送到/message/xxx地址
        registry.setApplicationDestinationPrefixes("/message");
        //服务端广播消息的路径前缀,客户端需要相应订阅/topic/yyy这个地址的消息
        registry.enableSimpleBroker("/topic");
        //给指定用户发送消息的路径前缀,默认值是/user/
        registry.setUserDestinationPrefix("/user/");
    }
 
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(myChannelInterceptor);
    }
 
}

6. 示例页面

<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Chat With STOMP Message</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <script th:src="@{/layui/lay/modules/layer.js}"></script>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <link th:href="@{/layui/css/modules/layer/default/layer.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
    <style type="text/css">
        #connect-container {
            margin: 0 auto;
            width: 400px;
        }
 
        #connect-container div {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
 
        .message input {
            padding: 5px;
            margin: 0 7px 10px 0;
        }
 
        .layui-btn {
            display: inline-block;
        }
    </style>
    <script type="text/javascript">
        var stompClient = null;
 
        $(function () {
            var target = $("#target");
            if (window.location.protocol === 'http:') {
                target.val('http://' + window.location.host + target.val());
            } else {
                target.val('https://' + window.location.host + target.val());
            }
        });
 
        function setConnected(connected) {
            var connect = $("#connect");
            var disconnect = $("#disconnect");
            var echo = $("#echo");
 
            if (connected) {
                connect.addClass("layui-btn-disabled");
                disconnect.removeClass("layui-btn-disabled");
                echo.removeClass("layui-btn-disabled");
            } else {
                connect.removeClass("layui-btn-disabled");
                disconnect.addClass("layui-btn-disabled");
                echo.addClass("layui-btn-disabled");
            }
 
            connect.attr("disabled", connected);
            disconnect.attr("disabled", !connected);
            echo.attr("disabled", !connected);
        }
 
        //连接
        function connect() {
            var target = $("#target").val();
 
            var ws = new SockJS(target);
            stompClient = Stomp.over(ws);
 
            stompClient.connect({}, function () {
                setConnected(true);
                log('Info: STOMP connection opened.');
 
                //连接成功后,主动拉取未读消息
                pullUnreadMessage("/topic/reply");
 
                //订阅服务端的/topic/reply地址
                stompClient.subscribe("/user/topic/reply", function (response) {
                    log(JSON.parse(response.body).content);
                })
            },function () {
                //断开处理
                setConnected(false);
                log('Info: STOMP connection closed.');
            });
        }
 
        //断开连接
        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
                stompClient = null;
            }
            setConnected(false);
            log('Info: STOMP connection closed.');
        }
 
        //向指定用户发送消息
        function sendMessage() {
            if (stompClient != null) {
                var receiver = $("#receiver").val();
                var msg = $("#message").val();
                log('Sent: ' + JSON.stringify({'receiver': receiver, 'msg':msg}));
 
                $.ajax({
                    url: "/wsTemplate/sendToUser",
                    type: "POST",
                    dataType: "json",
                    async: true,
                    data: {
                        "receiver": receiver,
                        "msg": msg
                    },
                    success: function (data) {
 
                    }
                });
            } else {
                layer.msg('STOMP connection not established, please connect.', {
                    offset: 'auto'
                    ,icon: 2
                });
            }
        }
 
        //从服务器拉取未读消息
        function pullUnreadMessage(destination) {
            $.ajax({
                url: "/wsTemplate/pullUnreadMessage",
                type: "POST",
                dataType: "json",
                async: true,
                data: {
                    "destination": destination
                },
                success: function (data) {
                    if (data.result != null) {
                        $.each(data.result, function (i, item) {
                            log(JSON.parse(item).content);
                        })
                    } else if (data.code !=null && data.code == "500") {
                        layer.msg(data.msg, {
                            offset: 'auto'
                            ,icon: 2
                        });
                    }
                }
            });
        }
 
        //日志输出
        function log(message) {
            console.debug(message);
        }
    </script>
</head>
<body>
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being
        enabled. Please enable
        Javascript and reload this page!</h2></noscript>
    <div>
        <div id="connect-container" class="layui-elem-field">
            <legend>Chat With STOMP Message</legend>
            <div>
                <input id="target" type="text" class="layui-input" size="40" style="width: 350px" value="/chat-websocket"/>
            </div>
            <div>
                <button id="connect" class="layui-btn layui-btn-normal" onclick="connect();">Connect</button>
                <button id="disconnect" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="disconnect();">Disconnect
                </button>
 
            </div>
            <div class="message">
                <input id="receiver" type="text" class="layui-input" size="40" style="width: 350px" placeholder="接收者姓名" value=""/>
                <input id="message" type="text" class="layui-input" size="40" style="width: 350px" placeholder="消息内容" value=""/>
            </div>
            <div>
                <button id="echo" class="layui-btn layui-btn-normal layui-btn-disabled" disabled="disabled"
                        onclick="sendMessage();">Send Message
                </button>
            </div>
        </div>
    </div>
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1527405.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mac npm install 很慢或报错

npm ERR! code CERT_HAS_EXPIRED npm ERR! errno CERT_HAS_EXPIRED npm ERR! request to https://registry.npm.taobao.org/pnpm failed, reason: certificate has expired 1、取消ssl验证&#xff1a; npm config set strict-ssl false 修改后一般就可以了&#xff0c;…

BootScrap详细教程

文章目录 前言一、BootScrap入门二、导航三、栅格系统四、container五、面板六、媒体对象七、分页八、图标九、实现动态效果 前言 BootScrap是别人帮我们写好的CSS样式。如果想要使用BootScrap&#xff0c;需要先下载下来&#xff0c;在页面上引入&#xff0c;编写HTML需要按照…

【实验01 扩展实验】C#桌面项目:简易计算器

【实验要求】 &#xff08;1&#xff09;新建一个C#桌面项目Calc&#xff0c;实现简易计算器功能&#xff0c;界面如图1所示。 &#xff08;2&#xff09;计算方式&#xff1a;通过点击对应的按钮&#xff0c;输入第1个数&#xff08;可以是整数或实数&#xff09;&#xff0c…

配置LVS NAT模式

配置LVS NAT模式 环境准备 client1&#xff1a;eth0->192.168.88.10&#xff0c;网关192.168.88.5lvs1: eth0 -> 192.168.88.5&#xff1b;eth1->192.168.99.5web1&#xff1a;eth1->192.168.99.100&#xff1b;网关192.168.99.5web2&#xff1a;eth1->192.168…

【推荐】免费AI论文写作-「智元兔 AI」

还在为写论文焦虑&#xff1f;免费AI写作大师来帮你三步搞定&#xff01; 智元兔AI是ChatGPT的人工智能助手&#xff0c;并且具有出色的论文写作能力。它能够根据用户提供的题目或要求&#xff0c;自动生成高质量的论文。 不论是论文、毕业论文、散文、科普文章、新闻稿件&…

内置泵电源,热保护电路等功能的场扫描电路D78040,偏转电流可达1.7Ap-p,可用于中小型显示器。

D78040是一款场扫描电路&#xff0c;偏转电流可达1.7Ap-p&#xff0c;可用于中小型显示器。 二 特 点 1、有内置泵电源 2、垂直输出电路 3、热保护电路 4、偏转电流可达1.7Ap-p 三 基本参数 四 应用电路图 1、应用线路 2、PIN5脚输出波形如下&#xff1a;

顶顶通呼叫中心中间件-群集配置方法讲解(mod_cti基于FreeSWITCH)

群集介绍 比较多的外呼或呼入系统&#xff0c;假如整个系统需要1万并发&#xff0c;单机最高就3000-5000并发&#xff0c;这时就需要多机群集了。顶顶通呼叫中心中间件使用redis数据库&#xff0c;多个FreeSWITHC(mod_cti)连接同一个redis就可以很容易的配置成群集系统。 想了…

java Flink(四十二)Flink的序列化以及TypeInformation介绍(源码分析)

Flink的TypeInformation以及序列化 TypeInformation主要作用是为了在 Flink系统内有效地对数据结构类型进行管理&#xff0c;能够在分布式计算过程中对数据的类型进行管理和推断。同时基于对数据的类型信息管理&#xff0c;Flink内部对数据存储也进行了相应的性能优化。 Flin…

【DL经典回顾】激活函数大汇总(二十一)(BReLU附代码和详细公式)

激活函数大汇总&#xff08;二十一&#xff09;&#xff08;BReLU附代码和详细公式&#xff09; 更多激活函数见激活函数大汇总列表 一、引言 欢迎来到我们深入探索神经网络核心组成部分——激活函数的系列博客。在人工智能的世界里&#xff0c;激活函数扮演着不可或缺的角色…

深度学习面经-part3(RNN、LSTM)

3.RNN 核心思想&#xff1a;像人一样拥有记忆能力。用以往的记忆和当前的输入&#xff0c;生成输出。 RNN 和 传统神经网络 最大的区别:在于每次都会将前一次的输出结果&#xff0c;带到下一次的隐藏层中&#xff0c;一起训练。 RNN应用场景: 1.文本生成 2.语音识别 3.机器翻…

【DataWhale学习笔记-蝴蝶书共读】大语言模型背后

从图灵测试到ChatGPT 1950年&#xff0c;艾伦•图灵(Alan Turing)发表论文《计算机器与智能》&#xff08; Computing Machinery and Intelligence&#xff09;&#xff0c;提出并尝试回答“机器能否思考”这一关键问题。在论文中&#xff0c;图灵提出了“模仿游戏”&#xff…

RabbitMQ介绍及搭建

架构 RabbitMQ是实现了高级消息队列协议&#xff08;AMQP&#xff09;的开源消息代理软件&#xff0c;使用erlang语言编写&#xff0c;依赖Erlang环境运行。 Broker&#xff1a;运行消息队列服务进程的节点&#xff0c;包含Exchange、Queue&#xff1b; Producer&#xff1a;消…

自学Python第二十九天-feapder框架创建爬虫

自学Python第二十九天-feapder框架创建爬虫 安装feapder 的设计架构feapder 框架的简单使用简单创建爬虫简单爬取数据简单的数据保存 中间件校验浏览器渲染使用浏览器渲染获取接口数据 feapder是一款上手简单&#xff0c;功能强大的 Python爬虫框架&#xff0c;内置 AirSpide…

Games101笔记-模型、视图、投影

在旋转点&#xff0c;旋转矩阵的逆等于矩阵的转置 视图变换和投影变换 三维变换 左边3*3是线性变换&#xff0c;右边一列是仿射变换(平移) 先线性再平移 缩放、旋转、平移 x叉乘y得到z&#xff0c;y叉乘z得到x&#xff0c; xyz给任何两个可以得到另一个 (循环对称) z叉乘x得…

EDI在汽车主机厂配送流程中的应用

汽车主机厂的汽车配送流程始于汽车 “生产结束 ” &#xff0c;止于 “交付给经销商 ” 。在这个流程中&#xff0c;企业作为主机厂的下游供应商&#xff0c;与主机厂的物流服务供应商之间的信息交换将会变得十分重要。 配送流程&#xff1a;运输订单以及报告 汽车主机厂提供预…

6-高维空间:机器如何面对越来越复杂的问题

声明 本文章基于哔哩哔哩付费课程《小白也能听懂的人工智能原理》。仅供学习记录、分享&#xff0c;严禁他用&#xff01;&#xff01;如有侵权&#xff0c;请联系删除 目录 一、知识引入 &#xff08;一&#xff09;二维输入数据 &#xff08;二&#xff09;数据特征维度 …

Java-JVM 虚拟机原理调优实战

一、基础 栈帧&#xff08;Stack Frame&#xff09;栈空间的 基本元素&#xff0c;用于 方法的调用和方法的执行的数据结构 堆内存用来存放由new创建的对象和数组。在堆中分配的内存&#xff0c;由Java虚拟机的自动垃圾回收器来管理。在堆中产生了一个数组或对象后&#xff0c…

小白向-使用git实现不同服务器改动的同步

背景 深度学习项目&#xff0c;已有可运行的backbone&#xff0c;已将此项目在github建库。 需要使用不同分支进行不同改动的测试&#xff1b;有两台服务器可供程序运行&#xff1b; 项目需求 以github云端仓库为媒介&#xff0c;实现不同服务器改动无痛关联。维护项目代码…

MS14_064 漏洞利用与安全加固

文章目录 环境说明1 MS14_064 简介2 MS14_064 复现过程3 MS14_064 安全加固 环境说明 渗透机操作系统&#xff1a;kali-linux-2024.1-installer-amd64漏洞复现操作系统: sc_winxp_pro_with_sp2 1 MS14_064 简介 要利用此漏洞则需要进行用户交互。通过发送电子邮件信息给本地登…

【云开发笔记No.4】DevOps的起源,定义和基本原则

DevOps&#xff0c;作为一组过程、方法与系统的统称&#xff0c;它的出现并不是偶然的&#xff0c;而是源于软件开发与运维领域长期以来所面临的挑战和痛点。其诞生背景可以追溯到敏捷开发模式的兴起以及持续开发所带来的运维问题。随着软件行业的飞速发展&#xff0c;传统的软…