Javascript 如何将websocket推送计时器嵌入网页?

Javascript 如何将websocket推送计时器嵌入网页?,javascript,java,html,websocket,Javascript,Java,Html,Websocket,我正在学习使用Web套接字,并遵循以下示例: 事情按预期进行。但我的问题是,如何将计时器嵌入网页,我的代码如下所示: <html> <head> <title>WebSocket Page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <ce

我正在学习使用Web套接字,并遵循以下示例:

事情按预期进行。但我的问题是,如何将计时器嵌入网页,我的代码如下所示:

<html>
  <head>
    <title>WebSocket Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
  <center>
    <h1>Hello World!</h1>
    <p id="demo"></p>
    Time : <p id="time"></p>
    <script type="text/javascript" src="WebSocketClient.js"></script>
    <script>
      var client = new WebSocketClient('ws', '127.0.0.1', 8080, '/Dir_WebSocket/endpoint?push=TIME');
      client.connect();
      document.getElementById("demo").innerHTML = client.present();
//      document.getElementById("time").innerHTML = client.getServerUrl();
      document.getElementById('time').value = client.getServerUrl();      // How to show time here ?
    </script>
    </center>
  </body>
</html>
=====================================

class WebSocketClient
{
  constructor(protocol, hostname, port, endpoint)
  {
    this.webSocket = null;
    this.protocol = protocol;
    this.hostname = hostname;
    this.port = port;
    this.endpoint = endpoint;
  }

  getServerUrl() { return this.protocol + "://" + this.hostname + ":" + this.port + this.endpoint; }

  present() { return "ServerUrl = " + this.getServerUrl(); }

  connect()
  {
    try
    {
      this.webSocket = new WebSocket(this.getServerUrl());

      // Implement WebSocket event handlers!
      this.webSocket.onopen = function (event)
      {
        console.log('onopen::' + JSON.stringify(event, null, 4));
      };

      this.webSocket.onmessage = function (event)
      {
        var msg = event.data;
        console.log('onmessage :: ' + JSON.stringify(msg, null, 4));
      };
      this.webSocket.onclose = function (event)
      {
        console.log('onclose::' + JSON.stringify(event, null, 4));
      };
      this.webSocket.onerror = function (event)
      {
        console.log('onerror::' + JSON.stringify(event, null, 4));
      };

    }
    catch (exception)
    {
      console.error(exception);
    }
  }

  getStatus()
  {
    return this.webSocket.readyState;
  }

  send(message)
  {
    if (this.webSocket.readyState == WebSocket.OPEN)
    {
      this.webSocket.send(message);
    }
    else
    {
      console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
    }
  }

  disconnect()
  {
    if (this.webSocket.readyState == WebSocket.OPEN)
    {
      this.webSocket.close();
    }
    else
    {
      console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
    }
  }
}
import java.util.*;
import javax.websocket.Session;

public class PushTimeService implements Runnable
{
    private static PushTimeService instance;
    private static Map<String,Session> sMap = new HashMap<String,Session>();

    private PushTimeService()   {   }

    public static void add(Session s)   {   sMap.put(s.getId(),s); }

    public static void initialize()
    {
        if (instance == null)
        {
            instance = new PushTimeService();
            new Thread(instance).start();
        }
    }

    @Override
    public void run()
    {
        while (true)
        {
            try
            {
                Thread.sleep(10 * 1000);
                for (String key : sMap.keySet())
                {
                    Session s = sMap.get(key);

                    if (s.isOpen())
                    {
                        Date d = new Date(System.currentTimeMillis());
                        s.getBasicRemote().sendText(d.toString());
                    }
                    else sMap.remove(key);
                }
            }
            catch (Exception e) {   e.printStackTrace(); }
        }
    }
}
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/endpoint")
public class MyWebSocket
{
    private static PushTimeService pst;

    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("onOpen::" + session.getId());

        // Access request parameters from URL query String. If a client subscribes, add Session to PushTimeService. 
        Map<String,List<String>> params = session.getRequestParameterMap();

        if (params.get("push") != null && (params.get("push").get(0).equals("TIME")))
        {
            PushTimeService.initialize();
            PushTimeService.add(session);
        }
    }

    @OnClose
    public void onClose(Session session)
    {
        System.out.println("onClose::" + session.getId());
    }

    @OnMessage
    public void onMessage(String message,Session session)
    {
        System.out.println("onMessage::From=" + session.getId() + " Message=" + message);

        try
        {
            session.getBasicRemote().sendText("Hello Client " + session.getId() + "!");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable t)
    {
        System.out.println("onError::" + t.getMessage());
    }
}
import java.util.*;
导入javax.websocket.Session;
公共类PushTimeService实现可运行
{
私有静态PushTimeService实例;
私有静态映射sMap=newhashmap();
私有PushTimeService(){}
公共静态void add(会话s){sMap.put(s.getId(),s);}
公共静态void initialize()
{
if(实例==null)
{
实例=新的PushTimeService();
新线程(实例).start();
}
}
@凌驾
公开募捐
{
while(true)
{
尝试
{
线程。睡眠(10*1000);
for(字符串键:sMap.keySet())
{
会话s=sMap.get(键);
if(s.isOpen())
{
日期d=新日期(System.currentTimeMillis());
s、 getBasicRemote().sendText(d.toString());
}
否则sMap。移除(键);
}
}
catch(异常e){e.printStackTrace();}
}
}
}
=====================================

class WebSocketClient
{
  constructor(protocol, hostname, port, endpoint)
  {
    this.webSocket = null;
    this.protocol = protocol;
    this.hostname = hostname;
    this.port = port;
    this.endpoint = endpoint;
  }

  getServerUrl() { return this.protocol + "://" + this.hostname + ":" + this.port + this.endpoint; }

  present() { return "ServerUrl = " + this.getServerUrl(); }

  connect()
  {
    try
    {
      this.webSocket = new WebSocket(this.getServerUrl());

      // Implement WebSocket event handlers!
      this.webSocket.onopen = function (event)
      {
        console.log('onopen::' + JSON.stringify(event, null, 4));
      };

      this.webSocket.onmessage = function (event)
      {
        var msg = event.data;
        console.log('onmessage :: ' + JSON.stringify(msg, null, 4));
      };
      this.webSocket.onclose = function (event)
      {
        console.log('onclose::' + JSON.stringify(event, null, 4));
      };
      this.webSocket.onerror = function (event)
      {
        console.log('onerror::' + JSON.stringify(event, null, 4));
      };

    }
    catch (exception)
    {
      console.error(exception);
    }
  }

  getStatus()
  {
    return this.webSocket.readyState;
  }

  send(message)
  {
    if (this.webSocket.readyState == WebSocket.OPEN)
    {
      this.webSocket.send(message);
    }
    else
    {
      console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
    }
  }

  disconnect()
  {
    if (this.webSocket.readyState == WebSocket.OPEN)
    {
      this.webSocket.close();
    }
    else
    {
      console.error('webSocket is not open. readyState=' + this.webSocket.readyState);
    }
  }
}
import java.util.*;
import javax.websocket.Session;

public class PushTimeService implements Runnable
{
    private static PushTimeService instance;
    private static Map<String,Session> sMap = new HashMap<String,Session>();

    private PushTimeService()   {   }

    public static void add(Session s)   {   sMap.put(s.getId(),s); }

    public static void initialize()
    {
        if (instance == null)
        {
            instance = new PushTimeService();
            new Thread(instance).start();
        }
    }

    @Override
    public void run()
    {
        while (true)
        {
            try
            {
                Thread.sleep(10 * 1000);
                for (String key : sMap.keySet())
                {
                    Session s = sMap.get(key);

                    if (s.isOpen())
                    {
                        Date d = new Date(System.currentTimeMillis());
                        s.getBasicRemote().sendText(d.toString());
                    }
                    else sMap.remove(key);
                }
            }
            catch (Exception e) {   e.printStackTrace(); }
        }
    }
}
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/endpoint")
public class MyWebSocket
{
    private static PushTimeService pst;

    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("onOpen::" + session.getId());

        // Access request parameters from URL query String. If a client subscribes, add Session to PushTimeService. 
        Map<String,List<String>> params = session.getRequestParameterMap();

        if (params.get("push") != null && (params.get("push").get(0).equals("TIME")))
        {
            PushTimeService.initialize();
            PushTimeService.add(session);
        }
    }

    @OnClose
    public void onClose(Session session)
    {
        System.out.println("onClose::" + session.getId());
    }

    @OnMessage
    public void onMessage(String message,Session session)
    {
        System.out.println("onMessage::From=" + session.getId() + " Message=" + message);

        try
        {
            session.getBasicRemote().sendText("Hello Client " + session.getId() + "!");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable t)
    {
        System.out.println("onError::" + t.getMessage());
    }
}
import java.io.IOException;
导入java.util.List;
导入java.util.Map;
导入javax.websocket.OnClose;
导入javax.websocket.OnError;
导入javax.websocket.OnMessage;
导入javax.websocket.OnOpen;
导入javax.websocket.Session;
导入javax.websocket.server.ServerEndpoint;
@ServerEndpoint(“/endpoint”)
公共类MyWebSocket
{
专用静态PushTimeService pst;
@奥诺彭
公共开放(会议)
{
System.out.println(“onOpen::”+session.getId());
//从URL查询字符串访问请求参数。如果客户端订阅,请将会话添加到PushTimeService。
Map params=session.getRequestParameterMap();
if(params.get(“push”)!=null&(params.get(“push”).get(0).equals(“TIME”))
{
PushTimeService.initialize();
添加(会话);
}
}
@一次
公共void onClose(会话)
{
System.out.println(“onClose::”+session.getId());
}
@OnMessage
公共void onMessage(字符串消息、会话)
{
System.out.println(“onMessage::From=“+session.getId()+”Message=“+Message”);
尝试
{
session.getBasicRemote().sendText(“Hello客户端”+session.getId()+“!”);
}
捕获(IOE异常)
{
e、 printStackTrace();
}
}
@一个错误
公共作废登记员(可丢弃的t)
{
System.out.println(“onError::”+t.getMessage());
}
}
好的,我想出来了:

  connect()
  {
    try
    {
      this.webSocket = new WebSocket(this.getServerUrl());

      // Implement WebSocket event handlers!
      this.webSocket.onopen = function (event)
      {
        console.log('onopen :: ' + JSON.stringify(event, null, 4));
      };

      this.webSocket.onmessage = function (event)
      {
        var msg = event.data;
        console.log('onmessage ::  ' + JSON.stringify(msg, null, 4));
        var output = document.getElementById("time");
        output.innerHTML = msg;
      };
      this.webSocket.onclose = function (event)
      {
        console.log('onclose :: ' + JSON.stringify(event, null, 4));
      };
      this.webSocket.onerror = function (event)
      {
        console.log('onerror :: ' + JSON.stringify(event, null, 4));
      };

    }
    catch (exception)
    {
      console.error(exception);
    }
  }