MQTT-Syslog-Adapter mit Websocket und Web-Formular
- MqttAdapter: eine Instanz, zwei gleichzeitige Broker-Verbindungen (je ein Topic) - SyslogDecoder: serialisierte SyslogMessage (inkl. Untertypen) erkennen, Filter sev >= WARNING - SyslogEndpoint: Websocket unter /syslog, Broadcast an alle Clients - ConfigServlet + index.html: Formular für Server/Topics und Websocket-Client - AdapterLifecycle: Adapter beim Start erzeugen, beim Stop trennen - AsciiChars, StructuredData, SyslogMessage.Message: Serializable, sonst ist eine SyslogMessage nicht serialisierbar - Adapter.java und MainServlet.java durch obige Klassen ersetzt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>marwe
parent
8c1c87af60
commit
dff3868a51
|
|
@ -4,42 +4,38 @@
|
|||
<artifactId>vs.pu02</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>Eclipse Paho Repo</id>
|
||||
<url>https://repo.eclipse.org/content/repositories/paho-releases/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>17</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>5.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.websocket</groupId>
|
||||
<artifactId>jakarta.websocket-api</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency><!-- für Unit-Tests -->
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency> <!--Paho-->
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>5.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.websocket</groupId>
|
||||
<artifactId>jakarta.websocket-api</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- NEU: MQTT-Client, kommt mit ins WAR -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<!-- Ende NEU -->
|
||||
<dependency><!-- für Unit-Tests -->
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
|
|
|||
|
|
@ -1,11 +0,0 @@
|
|||
package vs;
|
||||
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
|
||||
public class Adapter {
|
||||
MqttClient a;
|
||||
MqttClient b;
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
package vs;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* helper class for RFC 5424 (https://datatracker.ietf.org/doc/html/rfc5424)
|
||||
|
|
@ -8,7 +9,7 @@ package vs;
|
|||
* @author Sandro Leuchter
|
||||
*
|
||||
*/
|
||||
public abstract class AsciiChars {
|
||||
public abstract class AsciiChars implements Serializable{
|
||||
private final String value;
|
||||
|
||||
public String value() {
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
package vs;
|
||||
|
||||
import jakarta.servlet.annotation.WebServlet;
|
||||
import jakarta.servlet.http.*;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet("/hello")
|
||||
public class MainServlet extends HttpServlet {
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
response.setContentType("text/html");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html><body>Hello World</body></html>");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
package vs;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
|
@ -12,8 +13,8 @@ import java.util.List;
|
|||
* @author Sandro Leuchter
|
||||
*
|
||||
*/
|
||||
public class StructuredData {
|
||||
static public class Element {
|
||||
public class StructuredData implements Serializable {
|
||||
static public class Element implements Serializable {
|
||||
private final String name;
|
||||
private List<Param> parameters;
|
||||
|
||||
|
|
@ -101,7 +102,7 @@ public class StructuredData {
|
|||
}
|
||||
}
|
||||
|
||||
static public class Param {
|
||||
static public class Param implements Serializable {
|
||||
private final String name;
|
||||
// name: printable US-ASCII string ^[@=\]\"\s]+
|
||||
// "@" + private enterpise number "@\d+(\.\d+)*"
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ public class SyslogMessage implements Serializable {
|
|||
DEBUG;
|
||||
}
|
||||
|
||||
public static interface Message {
|
||||
public static interface Message extends Serializable {
|
||||
public Object message();
|
||||
|
||||
public int length();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,53 @@
|
|||
package vs;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
import vs.StructuredData.Element;
|
||||
import vs.SyslogMessage.Facility;
|
||||
import vs.SyslogMessage.Severity;
|
||||
import vs.SyslogMessage.TextMessage;
|
||||
|
||||
public class SyslogSender {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String[][] ziele = {
|
||||
{ "tcp://localhost:1883", "vs/a" },
|
||||
{ "tcp://localhost:1884", "vs/b" } };
|
||||
|
||||
for (String[] z : ziele) {
|
||||
MqttClient client = new MqttClient(z[0],
|
||||
MqttClient.generateClientId(), new MemoryPersistence());
|
||||
client.connect();
|
||||
|
||||
for (Severity sev : Severity.values()) {
|
||||
SyslogMessage msg = new SyslogMessage(
|
||||
Facility.SECURITY1, sev,
|
||||
new AsciiChars.L255("mymachine.example.com"),
|
||||
new AsciiChars.L048("su"),
|
||||
new AsciiChars.L128(""),
|
||||
new AsciiChars.L032("ID47"),
|
||||
new StructuredData().add(Element.newTimeQuality(true, true)),
|
||||
new TextMessage(sev + " über " + z[1]));
|
||||
client.publish(z[1], serialisieren(msg), 1, false);
|
||||
}
|
||||
client.publish(z[1], "nur Text".getBytes(), 1, false);
|
||||
System.out.println("gesendet an " + z[0] + " / " + z[1]);
|
||||
|
||||
client.disconnect();
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] serialisieren(Object o) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
|
||||
out.writeObject(o);
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package vs.adapter;
|
||||
|
||||
import jakarta.servlet.ServletContext;
|
||||
import jakarta.servlet.ServletContextEvent;
|
||||
import jakarta.servlet.ServletContextListener;
|
||||
import jakarta.servlet.annotation.WebListener;
|
||||
|
||||
@WebListener
|
||||
public class AdapterLifecycle implements ServletContextListener {
|
||||
|
||||
static final String ATTR = "mqttAdapter";
|
||||
|
||||
/** Holt den Adapter aus dem ServletContext. */
|
||||
static MqttAdapter adapter(ServletContext ctx) {
|
||||
return (MqttAdapter) ctx.getAttribute(ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
MqttAdapter adapter = new MqttAdapter(SyslogEndpoint::broadcast);
|
||||
sce.getServletContext().setAttribute(ATTR, adapter);
|
||||
System.out.println("MqttAdapter erzeugt");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
MqttAdapter adapter = adapter(sce.getServletContext());
|
||||
if (adapter != null) {
|
||||
adapter.close();
|
||||
}
|
||||
System.out.println("MqttAdapter geschlossen");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import jakarta.servlet.annotation.WebServlet;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet("/config")
|
||||
public class ConfigServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
req.setCharacterEncoding("UTF-8");
|
||||
MqttAdapter adapter = AdapterLifecycle.adapter(getServletContext());
|
||||
StringBuilder status = new StringBuilder();
|
||||
|
||||
for (int slot = 0; slot < MqttAdapter.SLOTS; slot++) {
|
||||
String server = trim(req.getParameter("server" + (slot + 1)));
|
||||
String topic = trim(req.getParameter("topic" + (slot + 1)));
|
||||
|
||||
if (server.isEmpty()) {
|
||||
adapter.disconnect(slot);
|
||||
status.append("Broker ").append(slot + 1).append(": getrennt\n");
|
||||
continue;
|
||||
}
|
||||
if (!server.contains("://")) {
|
||||
server = "tcp://" + server; // "localhost:1883" -> "tcp://localhost:1883"
|
||||
}
|
||||
try {
|
||||
adapter.connect(slot, server, topic.isEmpty() ? "#" : topic);
|
||||
status.append("Broker ").append(slot + 1).append(": verbunden mit ")
|
||||
.append(server).append(" (").append(topic).append(")\n");
|
||||
} catch (Exception e) {
|
||||
status.append("Broker ").append(slot + 1).append(": FEHLER ")
|
||||
.append(e.getMessage()).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
resp.setContentType("text/plain; charset=UTF-8");
|
||||
resp.getWriter().print(status);
|
||||
}
|
||||
|
||||
private static String trim(String s) {
|
||||
return s == null ? "" : s.strip();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
public class MqttAdapter {
|
||||
|
||||
public static final int SLOTS = 2;
|
||||
|
||||
private final MqttClient[] clients = new MqttClient[SLOTS];
|
||||
private final Consumer<String> ziel;
|
||||
|
||||
/** @param ziel bekommt den Text jeder weitergeleiteten Nachricht */
|
||||
public MqttAdapter(Consumer<String> ziel) {
|
||||
this.ziel = ziel;
|
||||
}
|
||||
|
||||
/** Verbindet Slot 0 oder 1 mit einem Broker und abonniert ein Topic. */
|
||||
public synchronized void connect(int slot, String server, String topic)
|
||||
throws MqttException {
|
||||
disconnect(slot); // alte Verbindung in diesem Slot vorher schließen
|
||||
|
||||
MqttClient client = new MqttClient(server,
|
||||
MqttClient.generateClientId(), new MemoryPersistence());
|
||||
|
||||
client.setCallback(new MqttCallback() {
|
||||
@Override
|
||||
public void messageArrived(String t, MqttMessage message) {
|
||||
verarbeite(message.getPayload());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
System.err.println("Slot " + slot + ": Verbindung verloren: " + cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
}
|
||||
});
|
||||
|
||||
client.connect();
|
||||
client.subscribe(topic, 1);
|
||||
clients[slot] = client;
|
||||
}
|
||||
|
||||
/** Trennt die Verbindung in diesem Slot (falls vorhanden). */
|
||||
public synchronized void disconnect(int slot) {
|
||||
MqttClient client = clients[slot];
|
||||
clients[slot] = null;
|
||||
if (client == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (client.isConnected()) {
|
||||
client.disconnect();
|
||||
}
|
||||
client.close();
|
||||
} catch (MqttException e) {
|
||||
System.err.println("Fehler beim Trennen: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean isConnected(int slot) {
|
||||
return clients[slot] != null && clients[slot].isConnected();
|
||||
}
|
||||
|
||||
/** Alle Verbindungen schließen (z.B. beim Herunterfahren). */
|
||||
public synchronized void close() {
|
||||
for (int i = 0; i < SLOTS; i++) {
|
||||
disconnect(i);
|
||||
}
|
||||
}
|
||||
|
||||
/** Auspacken, filtern, weitergeben. */
|
||||
void verarbeite(byte[] payload) {
|
||||
SyslogDecoder.decode(payload)
|
||||
.filter(SyslogDecoder::isRelevant)
|
||||
.ifPresent(m -> ziel.accept(m.toString()));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.util.Optional;
|
||||
|
||||
import vs.SyslogMessage;
|
||||
import vs.SyslogMessage.Severity;
|
||||
|
||||
public final class SyslogDecoder {
|
||||
|
||||
private SyslogDecoder() {
|
||||
// nur statische Methoden, keine Objekte nötig
|
||||
}
|
||||
|
||||
/** Bytes -> SyslogMessage, oder leer, wenn keine drinsteckt. */
|
||||
public static Optional<SyslogMessage> decode(byte[] payload) {
|
||||
if (payload == null || payload.length == 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try (ObjectInputStream in = new ObjectInputStream(
|
||||
new ByteArrayInputStream(payload))) {
|
||||
Object o = in.readObject();
|
||||
if (o instanceof SyslogMessage m) {
|
||||
return Optional.of(m);
|
||||
}
|
||||
return Optional.empty();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Decode-Fehler: " + e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** true für EMERGENCY, ALERT, CRITICAL, ERROR, WARNING */
|
||||
public static boolean isRelevant(SyslogMessage m) {
|
||||
return m.sev() != null
|
||||
&& m.sev().ordinal() <= Severity.WARNING.ordinal();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package vs.adapter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
import jakarta.websocket.OnClose;
|
||||
import jakarta.websocket.OnError;
|
||||
import jakarta.websocket.OnOpen;
|
||||
import jakarta.websocket.Session;
|
||||
import jakarta.websocket.server.ServerEndpoint;
|
||||
|
||||
@ServerEndpoint("/syslog")
|
||||
public class SyslogEndpoint {
|
||||
|
||||
// alle offenen Browser-Verbindungen (für alle Endpoint-Objekte gemeinsam)
|
||||
private static final Set<Session> SESSIONS = new CopyOnWriteArraySet<>();
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(Session session) {
|
||||
SESSIONS.add(session);
|
||||
System.out.println("WebSocket geöffnet, jetzt " + SESSIONS.size() + " Clients");
|
||||
}
|
||||
|
||||
@OnClose
|
||||
public void onClose(Session session) {
|
||||
SESSIONS.remove(session);
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable t) {
|
||||
SESSIONS.remove(session);
|
||||
}
|
||||
|
||||
/** Schickt den Text an alle verbundenen Browser. */
|
||||
public static void broadcast(String text) {
|
||||
for (Session s : SESSIONS) {
|
||||
synchronized (s) {
|
||||
try {
|
||||
if (s.isOpen()) {
|
||||
s.getBasicRemote().sendText(text);
|
||||
}
|
||||
} catch (IOException | IllegalStateException e) {
|
||||
SESSIONS.remove(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Syslog-Adapter</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Syslog-Adapter: MQTT → WebSocket</h1>
|
||||
|
||||
<h2>MQTT-Broker</h2>
|
||||
<form id="cfg">
|
||||
<p>Broker 1:
|
||||
<input name="server1" placeholder="tcp://localhost:1883" size="30">
|
||||
Topic: <input name="topic1" placeholder="vs/a">
|
||||
</p>
|
||||
<p>Broker 2:
|
||||
<input name="server2" placeholder="tcp://localhost:1884" size="30">
|
||||
Topic: <input name="topic2" placeholder="vs/b">
|
||||
</p>
|
||||
<button type="submit">Verbinden</button>
|
||||
</form>
|
||||
<pre id="cfgStatus"></pre>
|
||||
|
||||
<h2>Empfangene Syslog-Nachrichten (≥ WARNING)</h2>
|
||||
<p id="status">Websocket: verbinde …</p>
|
||||
<ul id="log"></ul>
|
||||
|
||||
<script>
|
||||
// ---------- Formular ----------
|
||||
document.getElementById('cfg').addEventListener('submit', async (e) => {
|
||||
e.preventDefault(); // Seite NICHT neu laden, sonst bricht der WebSocket ab
|
||||
const daten = new URLSearchParams(new FormData(e.target));
|
||||
document.getElementById('cfgStatus').textContent = 'verbinde …';
|
||||
const antwort = await fetch('config', { method: 'POST', body: daten });
|
||||
document.getElementById('cfgStatus').textContent = await antwort.text();
|
||||
});
|
||||
|
||||
// ---------- WebSocket-Client ----------
|
||||
const url = new URL('syslog', location.href);
|
||||
url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const ws = new WebSocket(url);
|
||||
|
||||
ws.onopen = () => document.getElementById('status').textContent = 'Websocket: verbunden';
|
||||
ws.onclose = () => document.getElementById('status').textContent = 'Websocket: getrennt';
|
||||
ws.onmessage = (event) => {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = event.data;
|
||||
document.getElementById('log').prepend(li);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
package vs;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import vs.SyslogMessage.Severity;
|
||||
|
||||
public class MqttEmpfaenger {
|
||||
|
||||
public static void main(String[] args) throws MqttException {
|
||||
String broker = "tcp://localhost:1883";
|
||||
String topic = "vs/test";
|
||||
|
||||
// 1. Client-Objekt erzeugen
|
||||
MqttClient client = new MqttClient(
|
||||
broker,
|
||||
MqttClient.generateClientId(),
|
||||
new MemoryPersistence());
|
||||
|
||||
// 2. Festlegen, was bei eingehenden Nachrichten passiert
|
||||
client.setCallback(new MqttCallback() {
|
||||
@Override
|
||||
public void messageArrived(String t, MqttMessage message) {
|
||||
byte[] payload = message.getPayload();
|
||||
try (ObjectInputStream in = new ObjectInputStream(
|
||||
new ByteArrayInputStream(payload))) {
|
||||
|
||||
Object o = in.readObject();
|
||||
|
||||
if (o instanceof SyslogMessage m) {
|
||||
if (m.sev().ordinal() <= Severity.WARNING.ordinal()) {
|
||||
System.out.println("WEITERLEITEN: " + m);
|
||||
} else {
|
||||
System.out.println("ignoriert (zu unwichtig): " + m.sev());
|
||||
}
|
||||
} else {
|
||||
System.out.println("ignoriert: Objekt, aber keine SyslogMessage");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("ignoriert: kein serialisiertes Objekt ("
|
||||
+ e.getClass().getSimpleName() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable cause) {
|
||||
System.out.println("Verbindung verloren: " + cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
// nur relevant, wenn wir selbst senden
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Verbinden und abonnieren
|
||||
client.connect();
|
||||
client.subscribe(topic);
|
||||
System.out.println("Verbunden mit " + broker + ", warte auf " + topic + " ...");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package vs;
|
||||
|
||||
import vs.adapter.MqttAdapter;
|
||||
|
||||
public class ZweiBrokerTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
MqttAdapter adapter = new MqttAdapter(text -> System.out.println("→ " + text));
|
||||
|
||||
adapter.connect(0, "tcp://localhost:1883", "vs/a");
|
||||
adapter.connect(1, "tcp://localhost:1884", "vs/b");
|
||||
System.out.println("Slot 0 verbunden: " + adapter.isConnected(0));
|
||||
System.out.println("Slot 1 verbunden: " + adapter.isConnected(1));
|
||||
System.out.println("Warte 60 Sekunden auf Nachrichten ...");
|
||||
|
||||
Thread.sleep(60_000);
|
||||
adapter.close();
|
||||
System.out.println("Beendet.");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue