目次
テスト用 WebSocket サーバーの作成
Node.js で簡単な WebSocket サーバーを用意します。
package.json
{
"dependencies": {
"ws": "^7.3.1"
}
}
index.js
const ws = require("ws");
const server = new ws.Server({ port: 3000 });
server.on("connection", (ws) => {
console.log("connected");
server.clients.forEach((client) => {
setInterval(() => {
client.send(new Date().toString());
}, 1000);
});
ws.on("message", (message) => {
server.clients.forEach((client) => {
client.send(message);
});
});
ws.on("close", () => {
console.log("close");
});
ws.on("error", (e) => {
console.error(e);
});
});
実行
$ node index.js
WebSocket クライアントの実装
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>
<groupId>com.example</groupId>
<artifactId>example</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>example</name>
<dependencies>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.17</version>
</dependency>
</dependencies>
</project>
src/main/java/com/example/Example.java
package com.example;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
public class Example {
public static void main(String[] args) throws IOException, DeploymentException, InterruptedException {
URI uri = URI.create("ws://localhost:3000");
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(WebSocketHandler.class, uri);
RemoteEndpoint.Basic basic = session.getBasicRemote();
basic.sendText("Hello");
Thread.sleep(3000);
session.close();
}
}
src/main/java/com/example/WebSocketHandler.java
package com.example;
import javax.websocket.*;
@ClientEndpoint
public class WebSocketHandler {
@OnError
public void onError(Session session, Throwable cause) {
System.err.println("error");
cause.printStackTrace();
}
@OnMessage
public void onMessage(String msg, Session session) {
System.out.println("message: " + msg);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("closed");
}
@OnOpen
public void onOpen(Session session) {
System.out.println("opened");
}
}
実行
$ mvn -q -e compile exec:java -Dexec.mainClass=com.example.Example
opened
message: Hello
message: Wed Sep 30 2020 09:28:08 GMT+0900 (GMT+09:00)
message: Wed Sep 30 2020 09:28:09 GMT+0900 (GMT+09:00)
message: Wed Sep 30 2020 09:28:10 GMT+0900 (GMT+09:00)
closed