繁体   English   中英

为什么websocket的以下代码(dukeetf2)不起作用?

[英]Why the following code (dukeetf2 ) of websocket does not work?

我已经下载了Oracle的dukeetf2教程,但是它不起作用(当我运行它时,虽然应该每秒更新一次页面,但是没有任何反应)。 看来浏览器发送请求,但正如我在控制台下面的结果不更新页面。

SEVERE: in init
INFO: Initializing EJB.
INFO: JTS5014: Recoverable JTS instance, serverId = [100]
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: CORE10010: Loading application org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT done in 6,908 ms
INFO: GlassFish Server Open Source Edition 3.1.2.2 (5) startup time : Felix (2,692ms), startup services(117,706ms), total(120,398ms)
INFO: JMX005: JMXStartupService had Started JMXConnector on JMXService URL service:jmx:rmi://Workstation9:8686/jndi/rmi://Workstation9:8686/jmxrmi
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
INFO: Grizzly Framework 1.9.50 started in: 2ms - bound to [0.0.0.0:8080]
INFO: [2] timers deleted for id: 90756774797901824
INFO: EJB5181:Portable JNDI names for EJB PriceVolumeBean: [java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean, java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean!javaeetutorial.web.dukeetf2.PriceVolumeBean]
SEVERE: in init
INFO: Initializing EJB.
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT was successfully deployed in 348 milliseconds.
INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
INFO: Grizzly Framework 1.9.50 started in: 3ms - bound to [0.0.0.0:8181]
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
.....

我已经下载了依赖项,目前在我的依赖项目录中有javaee-api-7.0.jar,activation-1.1.jar和javax.mail-1.5.0.jar。

的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>websocket</artifactId>
        <groupId>org.glassfish.javaeetutorial</groupId>
        <version>7.0.4-SNAPSHOT</version>
    </parent>

    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>dukeetf2</artifactId>
    <packaging>war</packaging>

    <name>dukeetf2</name>
</project>

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Duke's WebSocket ETF</title>
  <link rel="stylesheet" type="text/css" href="resources/css/default.css" />
  <script type="text/javascript">
      var wsocket;
      function connect() {
          wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
          wsocket.onmessage = onMessage;
      }
      function onMessage(evt) {
          var arraypv = evt.data.split(",");
          document.getElementById("price").innerHTML = arraypv[0];
          document.getElementById("volume").innerHTML = arraypv[1];
      }
      window.addEventListener("load", connect, false);
  </script>
</head>
<body>
    <h1>Duke's WebSocket ETF</h1>
    <table>
        <tr>
            <td width="100">Ticker</td>
            <td align="center">Price</td>
            <td id="price" style="font-size:24pt;font-weight:bold;">--.--</td>
        </tr>
        <tr>
            <td style="font-size:18pt;font-weight:bold;" width="100">DKEJ</td>
            <td align="center">Volume</td>
            <td id="volume" align="right">--</td>
        </tr>
    </table>
</body>
</html>

ETFEndpoint.java

package javaeetutorial.web.dukeetf2;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/* WebSocket version of the dukeetf example */
@ServerEndpoint("/dukeetf")
public class ETFEndpoint {
    private static final Logger logger = Logger.getLogger("ETFEndpoint");
    /* Queue for all open WebSocket sessions */
    static Queue<Session> queue = new ConcurrentLinkedQueue<>();

    /* PriceVolumeBean calls this method to send updates */
    public static void send(double price, int volume) {
        System.err.println("in send");

        String msg = String.format("%.2f, %d", price, volume);
        try {
            /* Send updates to all open WebSocket sessions */
            for (Session session : queue) {
                session.getBasicRemote().sendText(msg);
                logger.log(Level.INFO, "Sent: {0}", msg);
            }
        } catch (IOException e) {
            logger.log(Level.INFO, e.toString());
        }
    }

    @OnOpen
    public void openConnection(Session session) {
        System.err.println("in open connection");

        /* Register this connection in the queue */
        queue.add(session);
        logger.log(Level.INFO, "Connection opened.");
    }

    @OnClose
    public void closedConnection(Session session) {
        System.err.println("in closed connection");

        /* Remove this connection from the queue */
        queue.remove(session);
        logger.log(Level.INFO, "Connection closed.");
    }

    @OnError
    public void error(Session session, Throwable t) {
        System.err.println("in error");

        /* Remove this connection from the queue */
        queue.remove(session);
        logger.log(Level.INFO, t.toString());
        logger.log(Level.INFO, "Connection error.");
    }

}

PriceVolumeBean.java

    package javaeetutorial.web.dukeetf2;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

/* Updates price and volume information every second */
@Startup
@Singleton
public class PriceVolumeBean {
    /* Use the container's timer service */
    @Resource TimerService tservice;
    private Random random;
    private volatile double price = 100.0;
    private volatile int volume = 300000;
    private static final Logger logger = Logger.getLogger("PriceVolumeBean");

    @PostConstruct
    public void init() {
        /* Intialize the EJB and create a timer */
        System.err.println("in init");

        logger.log(Level.INFO, "Initializing EJB.");
        random = new Random();
        tservice.createIntervalTimer(1000, 1000, new TimerConfig());
    }

    @Timeout
    public void timeout() {
        System.err.println("in timeout");

        /* Adjust price and volume and send updates */
        price += 1.0*(random.nextInt(100)-50)/100.0;
        volume += random.nextInt(5000) - 2500;
        ETFEndpoint.send(price, volume);
    }
}

对于那些想知道我如何下载它的人,我使用了该地址和“ svn export”命令。

如前所述,您使用了与Java EE 7不兼容的Glassfish Server 3.1 您应该使用Glassfish 4.0服务器来运行上面的WebSocket示例。 WebSocket已随Java EE 7一起引入。

要知道如何运行此示例。 转到本教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM