精华内容
下载资源
问答
  • 我重写的![图片说明](https://img-ask.csdn.net/upload/201711/15/1510746548_122327.png)没有使用serverEndpoint标签
  • socket.onclose = function(res) { console.log("llws关闭连接!"); // heartContent(); // init(); } }); } ```![图片说明](https://img-ask.csdn.net/upload/201911/15/1573782215_619011.png) ...
  • SpringBoot WebSocket使用

    万次阅读 2018-03-17 15:34:18
    由于SpringBoot已经整合了WebSocket,使用起来非常方便。这篇博客的前提是已经搭建好SpringBoot项目,如果没有搭建好,请参考http://blog.csdn.net/u010889616/article/details/79561808这篇文章。项目结构如下:...

    由于SpringBoot已经整合了WebSocket,使用起来非常方便。这篇博客的前提是已经搭建好SpringBoot项目,如果没有搭建好,请参考http://blog.csdn.net/u010889616/article/details/79561808这篇文章。

    项目结构如下:

    gradle添加依赖

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket
        compile group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.0.0.RELEASE'

    (1)开启WebSocket服务。

    新建WebSocketConfig.java类,添加@Configuration注解

    package com.wzj.demo.websocket;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    /**
     * Created by wzj on 2018/3/14.
     */
    @Configuration
    public class WebSocketConfig
    {
        @Bean
        public ServerEndpointExporter serverEndpointExporter()
        {
            return new ServerEndpointExporter();
        }
    }
    
    (2)配置/websocket站点

    使用@ServerEndpoint注解来配置/websocket站点,来让前端访问,每一个函数都有注释。

    package com.wzj.demo.websocket;
    
    import org.springframework.stereotype.Component;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.List;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    /**
     * Created by wzj on 2018/3/14.
     */
    @ServerEndpoint(value = "/websocket")
    @Component
    public class MyWebSocket
    {
        /**
         * 在线人数
         */
        public static int onlineNumber = 0;
    
        /**
         * 所有的对象
         */
        public static List<MyWebSocket> webSockets = new CopyOnWriteArrayList<MyWebSocket>();
    
        /**
         * 会话
         */
        private Session session;
    
        /**
         * 建立连接
         *
         * @param session
         */
        @OnOpen
        public void onOpen(Session session)
        {
            onlineNumber++;
            webSockets.add(this);
    
            this.session = session;
    
            System.out.println("有新连接加入! 当前在线人数" + onlineNumber);
        }
    
        /**
         * 连接关闭
         */
        @OnClose
        public void onClose()
        {
            onlineNumber--;
            webSockets.remove(this);
            System.out.println("有连接关闭! 当前在线人数" + onlineNumber);
        }
    
        /**
         * 收到客户端的消息
         *
         * @param message 消息
         * @param session 会话
         */
        @OnMessage
        public void onMessage(String message, Session session)
        {
            System.out.println("来自客户端消息:" + message);
    
            sendMessage("欢迎连接");
        }
    
        /**
         * 发送消息
         *
         * @param message 消息
         */
        public void sendMessage(String message)
        {
            try
            {
                session.getBasicRemote().sendText(message);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    

    (3)在webapp/WEB-INF/jsp目录,新建index.jsp文件

    webSocket = new WebSocket("ws://localhost:8080/websocket");  //连接本地后台的/websocket服务

    webSocket有三个响应事件onopen(服务连通)、onmesage(收到消息)、onclose(连接被关闭)

    <%--
      Created by IntelliJ IDEA.
      User: wzj
      Date: 2016/10/8
      Time: 21:24
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Index</title>
    </head>
    <body>
    
        <div>你好</div>
        <div id="message"></div>
    
        <canvas id="canvas" style="border: 1px solid red;"></canvas>
    </body>
    </html>
    <script>
    
        var webSocket;
        if (window.WebSocket)
        {
            webSocket = new WebSocket("ws://localhost:8080/websocket");
    
            //连通之后的回调事件
            webSocket.onopen = function()
            {
                webSocket.send("发送数据");
            };
    
            //接收后台服务端的消息
            webSocket.onmessage = function (evt)
            {
                var received_msg = evt.data;
                alert("数据已接收:" + received_msg);
            };
    
            //连接关闭的回调事件
            webSocket.onclose = function()
            {
                alert("连接已关闭...");
            };
    
        }
    
    </script>
    

    (4)在Controller配置url,来访问index.jsp页面

    package com.wzj.demo.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * Created by wzj on 2018/3/14.
     */
    @RestController
    public class WelcomeController
    {
        /**
         * 首页
         * @return 测试
         */
        @RequestMapping(value = "/welcome")
        @ResponseBody
        public String welcome()
        {
            return "Hello World";
        }
    
        @RequestMapping(value = "/index")
        public ModelAndView index(ModelAndView view)
        {
            //设置jsp名字
            view.setViewName("index");
    
            //传递数据
            view.addObject("name","张三");
    
            return view;
        }
    }
    

    (5)测试

    启动SpingBoot,在浏览器输入http://127.0.0.1:8080/index,就会发现日志中打印出,有客户端连接,并收到消息。



    在浏览器端也收到消息


    Demo Github地址: https://github.com/HelloKittyNII/SpringBoot/tree/master/SpringBootDemo

    展开全文
  • Here is my WebSocket endpointimport javax.websocket....import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.Session;import javax.websocket.server.ServerEndpo...

    Here is my WebSocket endpoint

    import javax.websocket.CloseReason;

    import javax.websocket.OnClose;

    import javax.websocket.OnMessage;

    import javax.websocket.Session;

    import javax.websocket.server.ServerEndpoint;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import com.twitter.hbc.core.Client;

    @ServerEndpoint("/tweets")

    public class TweetStreamServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TweetStreamServer.class);

    @OnMessage

    public void tweets(final String message, final Session client) throws IOException, InterruptedException {

    LOGGER.debug("registering search term {}", message);

    final TwitterHoseBird twitterHoseBird = new TwitterHoseBird();

    final Client twitterClient = twitterHoseBird.getInstance(message);

    while(!twitterClient.isDone()) {

    client.getAsyncRemote().sendText(twitterHoseBird.getMsgQueue().take());

    }

    }

    @OnClose

    public void onClose(CloseReason reason) {

    System.out.println("Closing connection");

    LOGGER.warn("closing connection {}", reason);

    }

    }

    When I deploy this, I try to hit the endpoint via JavaScript code as

    var connection = new WebSocket('ws://127.0.0.1:8080/tweetstream-1.0-SNAPSHOT/tweets');

    connection.onmessage = function (e) {

    console.log('Server: ' + e.data);

    };

    connection.send('fifa');

    This starts to send tweets from the server. Now when I close the connection from client, I do

    connection.close();

    Problem?

    I want to close connection to twitter once websocket client connection closes. I expect the following code to execute

    @OnClose

    public void onClose(CloseReason reason) {

    System.out.println("Closing connection");

    LOGGER.warn("closing connection {}", reason);

    }

    But on server log, I do not see any such statement

    /Users/harith/code/installers/wildfly-8.1.0.Final/bin/standalone.sh

    =========================================================================

    /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/bin/java -classpath "/Applications/IntelliJ IDEA 13.app/lib/idea_rt.jar:/Applications/IntelliJ IDEA 13.app/lib/util.jar" -Dfile.encoding=UTF-8 com.intellij.rt.execution.CommandLineWrapper /private/var/folders/qs/y62p93xs0bdb9ptk6l2r8vw0002kvk/T/classpath571663656928489966.tmp com.intellij.javaee.oss.process.JavaeeProcess 53801 com.intellij.javaee.oss.jboss.agent.JBoss71Agent

    Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

    JBoss Bootstrap Environment

    [2014-07-12 02:16:06,305] Artifact tweetstream:war: Server is not connected. Deploy is not available.

    JBOSS_HOME: /Users/harith/code/installers/wildfly-8.1.0.Final

    Detected server admin port: 9990

    Detected server http port: 8080

    JAVA: /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/bin/java

    JAVA_OPTS: -server -Xms64m -Xmx512m -XX:MaxPermSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true

    =========================================================================

    [0m14:16:06,048 INFO [org.jboss.modules] (main) JBoss Modules version 1.3.3.Final

    [0m[0m14:16:06,289 INFO [org.jboss.msc] (main) JBoss MSC version 1.2.2.Final

    [0m[0m14:16:06,349 INFO [org.jboss.as] (MSC service thread 1-6) JBAS015899: WildFly 8.1.0.Final "Kenny" starting

    [0m[0m14:16:07,165 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS015888: Creating http management service using socket-binding (management-http)

    [0m[0m14:16:07,180 INFO [org.xnio] (MSC service thread 1-8) XNIO version 3.2.2.Final

    [0m[0m14:16:07,186 INFO [org.xnio.nio] (MSC service thread 1-8) XNIO NIO Implementation Version 3.2.2.Final

    [0m[0m14:16:07,207 INFO [org.jboss.as.security] (ServerService Thread Pool -- 45) JBAS013171: Activating Security Subsystem

    [0m[33m14:16:07,208 WARN [org.jboss.as.txn] (ServerService Thread Pool -- 46) JBAS010153: Node identifier property is set to the default value. Please make sure it is unique.

    [0m[0m14:16:07,211 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 32) JBAS010280: Activating Infinispan subsystem.

    [0m[0m14:16:07,213 INFO [org.wildfly.extension.io] (ServerService Thread Pool -- 31) WFLYIO001: Worker 'default' has auto-configured to 16 core threads with 128 task threads based on your 8 available processors

    [0m[0m14:16:07,219 INFO [org.jboss.as.naming] (ServerService Thread Pool -- 40) JBAS011800: Activating Naming Subsystem

    [0m[0m14:16:07,221 INFO [org.jboss.as.webservices] (ServerService Thread Pool -- 48) JBAS015537: Activating WebServices Extension

    [0m[0m14:16:07,222 INFO [org.jboss.as.security] (MSC service thread 1-13) JBAS013170: Current PicketBox version=4.0.21.Beta1

    [0m[0m14:16:07,222 INFO [org.jboss.as.jsf] (ServerService Thread Pool -- 38) JBAS012615: Activated the following JSF Implementations: [main]

    [0m[0m14:16:07,251 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 47) JBAS017502: Undertow 1.0.15.Final starting

    [0m[0m14:16:07,252 INFO [org.wildfly.extension.undertow] (MSC service thread 1-3) JBAS017502: Undertow 1.0.15.Final starting

    [0m[0m14:16:07,266 INFO [org.jboss.as.connector.logging] (MSC service thread 1-11) JBAS010408: Starting JCA Subsystem (IronJacamar 1.1.5.Final)

    [0m[0m14:16:07,291 INFO [org.jboss.remoting] (MSC service thread 1-8) JBoss Remoting version 4.0.3.Final

    [0m[0m14:16:07,291 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)

    [0m[0m14:16:07,299 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-5) JBAS010417: Started Driver service with driver-name = h2

    [0m[0m14:16:07,346 INFO [org.jboss.as.naming] (MSC service thread 1-15) JBAS011802: Starting Naming Service

    [0m[0m14:16:07,346 INFO [org.jboss.as.mail.extension] (MSC service thread 1-13) JBAS015400: Bound mail session [java:jboss/mail/Default]

    [0m[0m14:16:07,390 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 47) JBAS017527: Creating file handler for path /Users/harith/code/installers/wildfly-8.1.0.Final/welcome-content

    [0m[0m14:16:07,425 INFO [org.wildfly.extension.undertow] (MSC service thread 1-1) JBAS017525: Started server default-server.

    [0m[0m14:16:07,498 INFO [org.wildfly.extension.undertow] (MSC service thread 1-13) JBAS017531: Host default-host starting

    [0m[0m14:16:07,561 INFO [org.wildfly.extension.undertow] (MSC service thread 1-2) JBAS017519: Undertow HTTP listener default listening on /127.0.0.1:8080

    [0m[0m14:16:07,724 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-13) JBAS015012: Started FileSystemDeploymentService for directory /Users/harith/code/installers/wildfly-8.1.0.Final/standalone/deployments

    [0m[0m14:16:07,728 INFO [org.jboss.as.server.deployment] (MSC service thread 1-3) JBAS015876: Starting deployment of "4f0c2559-5f61-4cf1-b441-c6288b419b80.war" (runtime-name: "4f0c2559-5f61-4cf1-b441-c6288b419b80.war")

    [0m[0m14:16:07,736 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-6) JBAS010400: Bound data source [java:jboss/datasources/ExampleDS]

    [0m[0m14:16:07,918 INFO [org.jboss.ws.common.management] (MSC service thread 1-8) JBWS022052: Starting JBoss Web Services - Stack CXF Server 4.2.4.Final

    [0m[0m14:16:08,062 INFO [io.undertow.websockets.jsr] (MSC service thread 1-11) UT026003: Adding annotated server endpoint class com.self.tweetstream.TweetStreamServer for path /tweets

    [0m[0m14:16:08,075 INFO [io.undertow.websockets.jsr] (MSC service thread 1-11) UT026004: Adding annotated client endpoint class com.self.tweetstream.TweetStreamClient

    [0m[0m14:16:08,167 INFO [org.wildfly.extension.undertow] (MSC service thread 1-11) JBAS017534: Registered web context: /4f0c2559-5f61-4cf1-b441-c6288b419b80

    [0m[0m14:16:08,203 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS018559: Deployed "4f0c2559-5f61-4cf1-b441-c6288b419b80.war" (runtime-name : "4f0c2559-5f61-4cf1-b441-c6288b419b80.war")

    [0m[0m14:16:08,215 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:9990/management

    [0m[0m14:16:08,215 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:9990

    [0m[0m14:16:08,216 INFO [org.jboss.as] (Controller Boot Thread) JBAS015874: WildFly 8.1.0.Final "Kenny" started in 2554ms - Started 250 of 304 services (91 services are lazy, passive or on-demand)

    [0mConnected to server

    [2014-07-12 02:16:08,683] Artifact tweetstream:war: Artifact is being deployed, please wait...

    [0m14:16:08,794 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "tweetstream-1.0-SNAPSHOT.war" (runtime-name: "tweetstream-1.0-SNAPSHOT.war")

    [0m[0m14:16:09,408 INFO [org.jboss.weld.deployer] (MSC service thread 1-5) JBAS016002: Processing weld deployment tweetstream-1.0-SNAPSHOT.war

    [0m[0m14:16:09,450 INFO [org.hibernate.validator.internal.util.Version] (MSC service thread 1-5) HV000001: Hibernate Validator 5.1.0.Final

    [0m[0m14:16:09,548 INFO [org.jboss.weld.deployer] (MSC service thread 1-14) JBAS016005: Starting Services for CDI deployment: tweetstream-1.0-SNAPSHOT.war

    [0m[0m14:16:09,573 INFO [org.jboss.weld.Version] (MSC service thread 1-14) WELD-000900: 2.1.2 (Final)

    [0m[0m14:16:09,580 INFO [org.jboss.weld.deployer] (MSC service thread 1-1) JBAS016008: Starting weld service for deployment tweetstream-1.0-SNAPSHOT.war

    [0m[0m14:16:10,361 INFO [io.undertow.websockets.jsr] (MSC service thread 1-8) UT026004: Adding annotated client endpoint class com.self.tweetstream.TweetStreamClient

    [0m[0m14:16:10,364 INFO [io.undertow.websockets.jsr] (MSC service thread 1-8) UT026003: Adding annotated server endpoint class com.self.tweetstream.TweetStreamServer for path /tweets

    [0m[0m14:16:10,383 INFO [javax.enterprise.resource.webcontainer.jsf.config] (MSC service thread 1-8) Initializing Mojarra 2.2.6-jbossorg-4 20140501-1134 for context '/tweetstream-1.0-SNAPSHOT'

    [0m[0m14:16:11,293 INFO [org.wildfly.extension.undertow] (MSC service thread 1-8) JBAS017534: Registered web context: /tweetstream-1.0-SNAPSHOT

    [0m[0m14:16:11,307 INFO [org.jboss.as.server] (management-handler-thread - 2) JBAS018559: Deployed "tweetstream-1.0-SNAPSHOT.war" (runtime-name : "tweetstream-1.0-SNAPSHOT.war")

    [0m[2014-07-12 02:16:11,327] Artifact tweetstream:war: Artifact is deployed successfully

    [2014-07-12 02:16:11,327] Artifact tweetstream:war: Deploy took 2,644 milliseconds

    [0m14:16:21,124 INFO [com.twitter.hbc.httpclient.BasicClient] (default task-2) New connection executed: tweetStream-client, endpoint: /1.1/statuses/filter.json?delimited=length&stall_warnings=true

    [0m[0m14:16:21,207 INFO [com.twitter.hbc.httpclient.ClientBase] (hosebird-client-io-thread-0) tweetStream-client Establishing a connection

    [0m[0m14:16:23,789 INFO [com.twitter.hbc.httpclient.ClientBase] (hosebird-client-io-thread-0) tweetStream-client Processing connection data

    [0m

    What am I missing here?

    UPDATE

    I have test as following

    @Test

    public void test() throws URISyntaxException, IOException, DeploymentException, InterruptedException {

    System.out.println("URI: " + getEndpointUrl());

    TweetStreamClient.latch = new CountDownLatch(1);

    Session session = connectToServer(TweetStreamClient.class, "tweets");

    assertNotNull(session);

    // (todo: harit) assert correct things

    // assertTrue(TweetStreamClient.latch.await(10, TimeUnit.SECONDS));

    // assertEquals("Hello", TweetStreamClient.response);

    }

    When I run this test, I see following in logs

    8295 [main] INFO io.undertow.websockets.jsr - UT026004: Adding annotated client endpoint class com.self.tweetstream.TweetStreamClient

    14:59:26,981 INFO [org.wildfly.extension.undertow] (MSC service thread 1-13) JBAS017535: Unregistered web context: /b5b7b561-8b49-4c69-b55f-7859b86da36d

    14:59:26,983 INFO [stdout] (default task-2) session id:AMAjTU1TYTCjXBgLOKnMXS6q, search term: Hello World!

    14:59:26,985 INFO [stdout] (default task-2) Closing session: io.undertow.websockets.jsr.UndertowSession@cd7ecfa

    14:59:26,986 WARN [com.self.tweetstream.TweetStreamServer] (default task-2) closing session: AMAjTU1TYTCjXBgLOKnMXS6q, reason: CloseReason[1001]

    But when I call connection.close() from JavaScript, I do not see such thing

    解决方案

    I was experiencing the same problem and initially thought it was a Wildfly issue, but then noticed that Firefox was triggering @OnClose. When I added an @OnError, Chromium was triggering that.

    I found an another StackOverflow question referring to the same behavior.

    It also appears that Chromium may have just fixed this issue as of a month ago.

    展开全文
  • ReactNative使用websocket实现实时聊天与web端使用websocket的写法一样,直接newWebSocket就可以。我在github上找到了两个有关RN的websocket组件包(react-native-websocket和react-native-reconnecting-websocket)...

    ReactNative使用websocket实现实时聊天与web端使用websocket的写法一样,直接new WebSocket就可以。我在github上找到了两个有关RN的websocket组件包(react-native-websocket和react-native-reconnecting-websocket),但是发现都是简单封装了原始websocket的API,并没有什么特殊的地方,所以我推荐大家直接使用原始websocket就可以。

    我在RN中使用websocket发现ws.onclose事件始终无法触发,ws.onmessage事件可以正常使用,所以网上很多断开重连的实现方法我这里是无法使用的。不知道大家有没有遇到这种情况。

    不过好在我这里(安卓手机)只要连上了,不管息屏亮屏还是后台运行,使用期间是不会断开的;(苹果手机)息屏了的话,是会断开的,如果用户一直是亮屏使用状态,那就不会断开,所以我这里加入了检测屏幕状态的监听,做一些逻辑判断,使每次亮屏就关闭之前的失效连接,再重新建立websocket连接。

    我们可以把有关websocket的代码全放在APP登陆后的首页文件中,这样APP运行的所有生命周期中,无论进入哪个页面,websocket连接始终存在。下面上代码:

    首先引入判断APP运行状态API的组件AppState、事件监听组件DeviceEventEmitter、判断运行系统组件Platform:

    import {
      StyleSheet,
      View,
      Platform,
      DeviceEventEmitter,
      AppState
    } from "react-native";

    下面是首页中有关websocket部分代码:

    class HomePage extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          Info: {},
          ws: {}
        };
        this.WebSocketConnect = this.WebSocketConnect.bind(this);
        this.handleAppStateChange = this.handleAppStateChange.bind(this);
      }
    
      async componentDidMount() {
        // 首次进入建立连接
        this.WebSocketConnect();
        // 添加监听前,先移除之前的监听
        AppState.removeEventListener('change', this.handleAppStateChange);
        // 添加APP运行状态监听
        AppState.addEventListener('change', this.handleAppStateChange);
      }
    
      componentWillUnmount() {
        // 组件销毁前,移除监听
        AppState.removeEventListener('change', this.handleAppStateChange);
      }
      //状态改变响应
      handleAppStateChange(appState) {
        // console.log('当前状态为:'+appState);
        // 只有ios系统才需要做状态处理
        if(Platform.OS === "ios"&&appState=="active"){
          // 建立前先关闭之前的废弃连接
          this.state.ws.close();
          this.WebSocketConnect();
          // ios 唤醒时补充请求一下数据
          DeviceEventEmitter.emit("sceneChange", {
            // 参数
          });
        }
      }
      WebSocketConnect() {
        var ws = null;
        ws = new WebSocket(
          "ws://11.111.111.11:90/GetWebSocket?Id=000001"
        );
        ws.onopen = e => {
          console.log("onopen", e);
        };
        ws.onmessage = evt => {
          console.log("onmessage", JSON.parse(evt.data));
          this.setState({
            Info: JSON.parse(evt.data)
          });
          DeviceEventEmitter.emit("sceneChange", {
            // 参数
          });
        };
        ws.onclose = e => {
          console.log("onclose", e);
        };
        ws.onerror = e => {
          console.log("onerror", e);
        };
        this.setState({
          ws: ws
        });
        ws = null
      }
    
      render() {
        return (
          <View>
            {/* 你的首页 */}
          </View>
        );
      }
    }
    

     

    展开全文
  • WebSocket的事件触发机制

    万次阅读 2018-01-10 22:11:59
    WebSocket API是纯事件驱动的。应用程序代码监听WebSocket对象上的事件,以便处理输入数据和连接状态的改变。WebSocket协议也是事件驱动的。客户端应用程序不需要轮询服务器来得到更新的数据。消息和事件将在服务器...

    WebSocket API是纯事件驱动的。应用程序代码监听WebSocket对象上的事件,以便处理输入数据和连接状态的改变。WebSocket协议也是事件驱动的。客户端应用程序不需要轮询服务器来得到更新的数据。消息和事件将在服务器发送它们的时候异步到达。

    WebSocket编程遵循异步编程模式,也就是说,只要WebSocket连接打开,应用程序就简单地监听事件。客户端不需要主动轮询服务器得到更多的信息。要开始监听事件,只要为WebSocket对象添加回调函数。也可以使用addEventListener() DOM方法为WebSocket对象添加事件监听器。

    WebSocket对象调度4个不同的事件:

     open

     message

     error

     close

    和所有Web API一样,可以用on<事件名称>处理程序属性监听这些事件,也可以使用addEventListener();方法。

    1. WebSocket事件:open

    一旦服务器响应了WebSocket连接请求,open事件触发并建立一个连接。open事件对应的回调函数称作onopen。

    代码清单2-4说明建立WebSocket连接时如何处理该事件。


     

    到open事件触发时,协议握手已经完成,WebSocket已经准备好发送和接收数据。如果应用程序接收到一个open事件,那么 可以确定WebSocket服务器成功地处理了连接请求,并且同意与应用程序通信。

    2. WebSocket事件:message

    WebSocket消息包含来自服务器的数据。你也可能听说过组成WebSocket消息的WebSocket帧(Frame)。第3章将详细讨论消息和帧的概念。为了理解消息使用API的方式,WebSocket API只输出完整的消息,而不是WebSocket帧。message事件在接收到消息时触发,对应于该事件的回调函数是onmessage。

    代码清单2-5展示了一个接收文本消息并显示消息内容的消息处理程序。


     

    除了文本,WebSocket消息还可以处理二进制数据,这种数据作为Blob消息(见代码清单2-6)或者ArrayBuffer消息处理(见代码清单2-7)。因为设置WebSocket消息二进制数据类型的应用程序会影响二进制消息,所以必须在读取数据之前决定用于客户端二进制输入数据的类型。

     

    3. WebSocket事件:error

    error事件在响应意外故障的时候触发。与该事件对应的回调函数为onerror。错误还会导致WebSocket连接关闭。如果你接收一个error事件,可以预期很快就会触发close事件。close事件中的代码和原因有时候能告诉你错误的根源。error事件处理程序是调用服务器重连逻辑以及处理来自WebSocket对象的异常的最佳场所。代码清单2-8展示了监听error事件的一个例子。



     

    4. WebSocket事件:close
    close事件在WebSocket连接关闭时触发。对应于close事件的回调函数是onclose。一旦连接关闭,客户端和服务器不再能接收或者发送消息。

    说明 WebSocket规范还定义了ping和pong帧,可以用于持续连接(keep-alive)、心跳、网络状态检测、延迟测量等,但是WebSocket API目前没有输出这些特性。尽管浏览器接受ping帧,但是不会触发对应WebSocket上的ping事件。相反,浏览器将自动响应pong帧。然而,浏览器实例化的ping如果在一段时间内没有得到pong应答,可能会触发连接的close事件。第8章将详细介绍WebSocket的ping和pong。

    当调用close()方法终止与服务器的连接时,也会触发onclose事件处理程序,如代码清单2-9所示。


     

    WebSocket close事件在连接关闭时触发,这可能有多种原因,比如连接失败或者成功的WebSocket关闭握手。WebSocket对象特性readyState反映了连接的状态(2为正在关闭,3为已关闭)。

    close事件有3个有用的属性(property),可以用于错误处理和恢复:wasClean、code和error。wasClean属性是一个布尔属性,表示连接是否顺利关闭。如果WebSocket的关闭是对来自服务器的一个close帧的响应,则该属性为true。如果连接是因为其他原因(例如,因为底层TCP连接关闭)关闭,则该属性为false。code和reason属性表示服务器发送的关闭握手状态。这些属性和WebSocket.close()方法中的code和reason参数一致,我们将在本章后面详加介绍。在第3章中,我们将在讨论WebSocket协议时讨论关闭的代码和它们的含义。

    说明 关于WebSocket事件的更多细节,参见WebSocket API规范:http://www.w3.org/TR/websockets/

    展开全文
  • WebSocket刨根问底(二)

    千次阅读 热门讨论 2017-08-29 10:00:03
    上篇文章【WebSocket刨根问底(一)】中我们对WebSocket的一些基本理论进行了介绍,但是并没有过多的涉及到一些实战的内容,今天我希望能够用几个简单的案例来向小伙伴们展示下WebSocket的一些具体用法。 WebSocket...
  • wx.onClose回调code1006该怎么办? 求大佬指教呀!!!!![图片说明](https://img-ask.csdn.net/upload/201901/10/1547107158_554409.jpg)
  • webSocket 示例

    2020-12-15 09:52:03
    JS部分: $(document).ready(function(){ socket(); }); ...function socket() ... let userId = parent.userId();... websocket = new WebSocket("ws://localhost:8081/webSocketFile/"+"data"+userI..
  • Fleck:C#Websocket实现

    2021-05-11 15:12:42
    斑点 Fleck是C#中的WebSocket服务器实现。 从项目分支出来的Fleck不需要继承,容器或其他引用。... OnClose = () => Console . WriteLine ( " Close! " ); socket . OnMessage = message => socket
  • 但是,如果程序现在正在执行WebSocket.send() ,则浏览器必须发现消息信号失败,因此将执行onclose函数。 当websocket断开连接时,后端websocket服务可能会发生错误,前端不会注意到收到的消息。 因此需要通过...
  • Java使用WebSocket

    2021-02-28 11:14:28
    之前有一篇WebSocket的视频通话教程,那个主要不是讲怎么使用WebSocket,这篇文章主要就说一下WebSocket的使用。首先要用到的是最新的Tomcat8,因为要支持JavaEE7,JavaEE7把WebSocket纳入规范的。下面是代码( 主要...
  • Websocket关闭连接

    千次阅读 2021-03-09 03:48:25
    本篇文章帮大家学习Websocket关闭连接,包含了Websocket关闭连接使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。关闭连接标志着服务器和客户端之间的通信结束。使用onclose事件可以...
  • 它在WebSocket对象的onclose事件监听器中使用. 构造器EDIT CloseEvent() 创建一个CloseEvent. 属性EDIT 该接口也继承了其父类Event的属性. CloseEvent.code只读 返回一个 unsigned short 类型的数字, 表示...
  • java WebSocket 实现

    2019-08-04 18:06:19
    一、 maven 主要依赖 <dependencies> <...-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api --> <dependency> <groupId>javax.websock...
  • OnClose = () => Console . WriteLine ( " Close! " ); socket . OnMessage = message => socket . Send ( message ); }); 支持的WebSocket版本 Fleck支持多种WebSocket版本的现代Web浏览器 Hixie-Draft-76 / ...
  • 关闭代码1006关闭websocket的原因

    千次阅读 2021-03-22 16:34:17
    websocket.onerror(evt)事件中查看详细信息。但是,Chrome很少会向JavaScript端报告任何接近代码1006的原因。这可能是由于WebSocket规范中的客户端安全规则所致,以防止滥用websocket。(例如使用它扫描目标服务器...
  • websocket-sharp中,我发现,如果在OnClose调用socket.Connect来实现socket的重连机制的话,会出现堆栈溢出的异常,所以,在这里我采用了使用timer来触发重连机制 using System; using System.Threading; using ...
  • 基于spring-boot-starter-websocket实现websocket
  • websocket系列:基于tio-websocket-spring-boot-starter实现
  • spring boot Websocket(使用笔记)

    千次阅读 2019-03-06 10:48:25
    转自:spring boot Websocket(使用笔记) 本文只作为个人笔记,大部分代码是引用其他人的文章的。 在springboot项目中使用websocket做推送,虽然挺简单的,但初学也踩过几个坑,特此记录。  使用websocket有两...
  • SpringBoot2+Netty+WebSocket(netty实现websocket,支持URL参数)

    万次阅读 多人点赞 2019-06-12 16:20:11
    * 通道组池,管理所有websocket连接 * @author zhengkai.blog.csdn.net * @date 2019-06-12 */ public class MyChannelHandlerPool { public MyChannelHandlerPool ( ) { } public static ...
  • websocket 心跳重连 (通信检测)

    万次阅读 热门讨论 2018-09-18 21:43:59
    最近做项目,用到websocket来做消息的实时推送。在做这个项目之前,websocket的相关内容没有接触过,只限于知道有这个东西。... websocket的基本事件有onopen、onmessage、onerror、onclose这四个事件,onopen是...
  • springboot+websocket实现服务端、客户端

    万次阅读 多人点赞 2019-01-12 12:54:43
    一、引言 小编最近一直在使用springboot框架...websocket主要功能就是实现网络通讯,比如说最经典的客服聊天窗口、您有新的消息通知,或者是项目与项目之间的通讯,都可以采用websocket来实现。 二、websocket介...
  • WebSocketClient objects are not reuseable You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to insure a successful cleanup. 今天主要解决如上这两个问题。 ...
  • Swoole WebServer服务端与客户端 持续更新简单WebServer 服务端实现简单WebServer ...$server = new Swoole\WebSocket\Server(&amp;amp;amp;amp;amp;quot;0.0.0.0&amp;amp;amp;amp;amp;quot;, 9906); //$
  • Golang如何使用websocket

    千次阅读 2018-06-16 12:21:10
    下载websocket包 $ go get golang.org/x/net/websocket 如果下载失败,可能是被墙了。 package golang.org/x/net/websocket: unrecognized import path “golang.org/x/net/websocket” ...
  • webSocket在spring的环境中是通过aop增强,是一个多例的bean。 主动调用关闭方法,实际是由代理类调用我们自己原先的onClose()方法,如果程序报错,关注自己的onClose方法即可。
  • java WebSocket客户端断线重连 | 实用代码框架

    万次阅读 多人点赞 2021-10-25 17:44:06
    在工作中是否会遇到实用websocket客户端连接服务端的时候,网络波动,服务端断连的情况。会导致客户端被动断开连接。为了解决这个问题,需要对被动断开连接的情况进行捕获,并重新创建连接。这篇文章主要是提供可以...
  • WebSocket 教程

    2020-12-19 03:21:34
    WebSocket 是一种网络通信协议,很多高级功能都需要它。本文介绍 WebSocket 协议的使用方法。一、为什么需要 WebSocket?初次接触 WebSocket 的人,都会问同样的问题:我们已经有了 HTTP 协议,为什么还需要另一个...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 17,991
精华内容 7,196
关键字:

onclosewebsocket

友情链接: M62446_vfd_yk.rar