Help us understand the problem. What is going on with this article?

これだけでOK WebSocket: Server=Java, Client=Java,JavaScript

Java製のWebSocket Serverに対し、
複数のJava WebSocket Client と JavaScript WebSocket Client が接続し、
クライアントからのメッセージは各クライアントに対してブロードキャストされるものと想定します。

動作確認済 Runtime

  1. Local Server : Tomcat 8.5
  2. Azure WebApp Service (Tomcat 9.0)

Server : Java

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/hellowebsocket")
public class ChatWebSocket {
    // 全てのクライアント
    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
    // メッセージを送信してきたクライアント
    private Session currentSession = null;
    /*
     * 接続がオープンしたとき
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig ec) {
        sessions.add(session);
        currentSession = session;
    }
    @OnMessage
    public String onMessage(String message) throws IOException {
        Iterator<Session> it = sessions.iterator();
        while (it.hasNext()) {
            Session s = it.next();
            if (s != currentSession) {
                s.getBasicRemote().sendText(message);
            }
        }
        return message;
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }
}

Client 1 : Java

import java.net.URI;
import java.util.Scanner;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
public class Client {
    public static void main(String[] args) throws Exception {
        String msg;
        Scanner scanIn = new Scanner(System.in);
        // 初期化のため WebSocket コンテナのオブジェクトを取得する
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        // サーバー・エンドポイントの URI
        URI uri = URI.create("ws://localhost:8080/hellowebsocket");
        // サーバー・エンドポイントとのセッションを確立する
        Session session = container.connectToServer(new WebSocketClientMain(), uri);

        while (true) {
            msg = scanIn.nextLine();
            session.getBasicRemote().sendText(msg);
            if (msg.equals("")) {
                break;
            }
        }
        scanIn.close();
        session.close();
    }
}

Client 1 : maven

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.glassfish.tyrus.bundles/tyrus-standalone-client -->
    <dependency>
        <groupId>org.glassfish.tyrus.bundles</groupId>
        <artifactId>tyrus-standalone-client</artifactId>
        <version>1.16</version>
    </dependency>
</dependencies>

Client 2 : JavaScript

<html>
<head>
<title>Chat</title>
<script type="text/javascript" src="./jquery.js"></script>
<script>
    var fullpath = document.location.pathname;
    var path = fullpath.substring(0, fullpath.lastIndexOf("/"));
    var url = "ws://" + document.location.host + path + "/hellowebsocket";
    var ws = new WebSocket(url); // 重要
    $(function() {
        $("#button-search").click(postChat);
        ws.onmessage = function(receive) {
            $("#message").text(receive.data);
        };
    });
    function postChat() {
        var text = $("#q").val();
        var state = ws.readyState;
        if (state == ws.OPEN) {
            ws.send(text);
        } else {
            alert("connection state is not OPEN: " + state);
        }
    }
</script>
</head>
<body>
    <div>
        <div id="inputform">
            <textarea id="q" cols="80" rows="2"></textarea>
            <input type="button" id="button-search" value="POST" />
        </div>
    </div>
    <div id="message"></div>
</body>
</html>
oyahiroki
Hiroki Oya <oyahiroki> 自然言語処理技術者 NLP Engineer (2001-2018) IBMで自然言語処理ソリューションの開発 (IBM Watson) (2018-現在) 日産自動車で自然言語処理ソリューションの開発 --- #NLP4J Java 自然言語処理
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした