Я учусь использовать Web Socket и следую этому примеру: https://www.pegaxchange.com/2018/01/28/websocket-server-java/
Все пошло так, как должно быть. Но мой вопрос: как мне встроить этот таймер в веб-страницу, мой код выглядит так:
<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());
}
}