This is all you need WebSocket: Server = Java, Client = Java, JavaScript

For Java WebSocket Server Multiple Java WebSocket Clients and JavaScript WebSocket Clients connect and We assume that messages from clients are broadcast to each client.

Operation confirmed 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 {
	//All clients
	private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
	//The client that sent the message
	private Session currentSession = null;
	/*
	 *When the connection opens
	 */
	@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);
		//Get the object of WebSocket container for initialization
		WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		//Server endpoint URI
		URI uri = URI.create("ws://localhost:8080/hellowebsocket");
		//Establish a session with the server endpoint
		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); //important
	$(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>

Recommended Posts

This is all you need WebSocket: Server = Java, Client = Java, JavaScript
[Java] Server Client Communication 1 (Unfinished)
Which Java HTTP client is better?
[Java] Can you explain this phenomenon?
[Java EE] Implement Client with WebSocket
Let's try WebSocket with Java and javascript!