LoginSignup
3
3

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

Last updated at Posted at 2020-03-26

【追記】改良版のコードが以下にあります。


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>
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3