Let's try WebSocket with Java and javascript!

Use Java and javascript (using jQuery)

  1. Write the server side in Java. If you read the comments in the code, you can understand the explanation of the contents.

WebSocketServer.java


package main.java;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

//With this, WebSocket Server
//URL can be wildcarded
@ServerEndpoint("/WebSocketServer")
public class WebSocketServer {

	//Session(communication)Map for saving
	private static Map<String, Session> session = new HashMap<>();

	//Variable to store your ID
	 String myId = "";

	 //Variable to store your name
	 String myName = "";

	/**
	 *Method called when connecting
	 */
	@OnOpen
	public void onOpen(final Session client, final EndpointConfig config) {
		/*Processing when establishing a session*/
		String log = client.getId() + " Was connected.";
		System.out.println(log);

	}

	/**
	 *Method called on error
	 */
	@OnError
	public void onError(final Session client, final Throwable error) {
		/*Processing when an error occurs*/
		String log = client.getId() + " was error. [" + error.getMessage() + "]";
		System.out.println(log);
	}

	/**
	 *Method called when disconnecting
	 */
	@OnClose
	public void onClose(final Session client, final CloseReason reason) throws IOException {
		/*Processing at session release*/
		String log = client.getId() + " was closed by " + reason.getCloseCode() + "[" + reason.getCloseCode().getCode()
				+ "]";
		System.out.println(log);
	}

	/**
	 *Method called when the message is called
	 */
	@OnMessage
	public void onMessage(final String text, final Session client) throws IOException {
		/*Processing when receiving a message*/
		System.out.println("WebSocket reception:" + text);

		//It is assumed that the content of the message is operated by separating line breaks and the id is described.
		String[] t = text.split("\n");
		String event = t[0];
		String id = t[1];

		System.out.println("EVENT:" + event);
		System.out.println("ID:" + id);
		switch (event) {

		case "login":
			//Save Session in HashMap
			session.put(id, client);
			//Store the ID in a variable.
			myId = id;

			//Cut out the name
			int strSize = id.length();
			int cutLength = 4;
			int nameCut = strSize - cutLength;
			//Save only name in variable
			myName = id.substring(0,nameCut);
			System.out.println("Cut out name:" + myName);

			//Send a string to the session saved by id
			Session mySession = session.get(id);
			mySession.getBasicRemote().sendText("Welcom to " + myName + " !!");
			System.out.println("login:" + id);
			break;

		case "commit":
			//broadcast
			for (Session s : session.values()) {
				s.getBasicRemote().sendText(myName + ": " + t[1]);
			}
			System.out.println("commit:" + t[1]);
			break;

		case "close":
			//Removed from session list
			System.out.println("ID to delete:" + myId);
			//Delete saved session
			session.remove(myId);
			System.out.println("close:Delete session");
			break;
		}
	}
}
  1. Write javascript on the client side. I would appreciate it if you could read the comments here as well.

script.js


$(function() {
	var url = 'ws://' + window.location.host + '/SampleServer/WebSocketServer';
    var ws = null;
    var inputId;
    console.log('Location:' + window.location.host);

		//Variable to generate a 4-digit random number
		var min = 1000;
		var max = 9999;

		//Salt code for attaching to a name and converting it to an ID
		var saltCode;

    //Press the initButton and it will run here
      $('#login').on("click",function() {
        if (ws == null) {
            inputId = $('#box1').find('input').val();
             //If the ID is empty, do not register
             if(inputId != "") {
            //Initialize Websocket
             ws = new WebSocket(url);
            //Event handler registration
             ws.onopen = onOpen;
             ws.onmessage = onMessage;
             ws.onclose = onClose;
             ws.onerror = onError;
             console.log("ID:" + inputId);
            } else {
                alert("Please enter your ID name!!");
            }
        }

      });

    //WebSocket open
    function onOpen(event) {
       $("#log").prepend("&lt;onopen&gt; " + "<br/>");
        console.log("WebSocket connection establishment");
				//Generate a 4-digit random integer
				saltCode = Math.floor(Math.random() * (max + 1 - min)) + min;
				//Explicitly cast to a string
				String(saltCode);
				//Create ID by attaching salt code
				inputId = inputId + saltCode;
				console.log('ID with salt code:' + inputId);
       ws.send("login\n" + inputId);
    };

    //WebSocket message
    function onMessage(receive) {
       $("#log").prepend(receive.data + "<br/><br/>");
        console.log("Response message:" + receive.data);
    };

    //WebSocket error
    function onError() {
        $("#log").prepend("&lt;onerror&gt; " + "<br/>");
        console.log("Error handling");
        alert("error");
    };

    //WebSocket close
    function onClose() {
        $("#log").prepend("&lt;onclose&gt; " + "<br/>");
        ws.send("close\ndelete")
        ws = null;
        console.log("WebSocket disconnection");
    };


    //window closed(Example:Closed the browser)Set time event
    $(window).on("beforeunload",function() {
        ws.onclose(); //WebSocket close
    });

    //Send a message to the server using WebSocket
   $('#send').on('click',function() {
       var sendMessage = $('#message').val();
       console.log("message:" + sendMessage);
       if(sendMessage != "") {
       ws.send("commit\n" + sendMessage);
           $('#message').val("");
       } else {
           console.log("I will not send it because it is empty");
       }
   });
});
  1. Prepare a simple html.

index.html


<!DOCTYPE html>

<html>
<head>
    <title>WebSocket Server Sample</title>
    <meta charset="utf-8"/>
    <script src="js/lib/jquery-3.4.1.min.js"></script>


    </head>
<body>
    <div id="box1">
    <input type="text" id="id" placeholder="inputID" />
    <button id="login">login</button>
        </div>
    <br/>
    <div id="box2">
    <input type="text" id="message" placeholder="inputMessage" />
        <button id="send">send</button>
        </div>
    <br/>
    <div id="log"></div>
    <script src="js/script.js"></script>
    </body>
</html>

I think it works like this.

スクリーンショット 2020-04-19 12.48.35.png

Log in as another user and send a message.

スクリーンショット 2020-04-19 12.52.09.png

You will receive a message. !! !!

スクリーンショット 2020-04-19 12.54.07.png

I can read the message properly.

Using webSocket in this way, we were able to create a simple chat system. It seems that interesting things can be created by linking with a database or building a system. The above is a simple websocket implementation.

Thank you for reading to the end.

Recommended Posts

Let's try WebSocket with Java and javascript!
Java and JavaScript
Try WebSocket with jooby
Let's scrape with Java! !!
Try to link Ruby and Java with Dapr
Let's experiment with Java inlining
Try DB connection with Java
Try calling JavaScript in Java
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Run Mosquitto with Docker and try WebSocket communication with MQTT
Socket communication with a web browser using Java and JavaScript ②
Socket communication with a web browser using Java and JavaScript ①
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Install Java and Tomcat with Ansible
[Java EE] Implement Client with WebSocket
Use JDBC with Java and Scala.
Try using Redis with Java (jar)
Output PDF and TIFF with Java 8
Try bidirectional communication with gRPC Java
Encrypt with Java and decrypt with C #
Create a high-performance enum with fields and methods like Java with JavaScript
Monitor Java applications with jolokia and hawtio
Link Java and C ++ code with SWIG
Try running MySql and Blazor with docker-compose
[Java] Reading and writing files with OpenCSV
HTTPS with Spring Boot and Let's Encrypt
Let's be lazy with inheritance and override
Let's summarize JavaScript, PHP, Java random functions
Try managing Java libraries with AWS CodeArtifact
Try using the Wii remote with Java
Let's study Java
Let's create a timed process with Java Timer! !!
Build and test Java + Gradle applications with Wercker
Pleiades Eclipse 2020-03 release ~ Java 14 Let's try new features!
[Swift vs Java] Let's understand static and final
JSON with Java and Jackson Part 2 XSS measures
Differences in writing Java, C # and Javascript classes
XXE and Java
Try local development of AWS (S3, DynamoDB) with AWS SDK for JavaScript and Docker
Prepare a scraping environment with Docker and Java
Try to implement TCP / IP + NIO with JAVA
Try drawing a cube with View and Layer
KMS) Envelope encryption with openssl and java decryption
Roughly try Java 9
Try debugging a Java program with VS Code
Encrypt / decrypt with AES256 in PHP and Java
[Java] Convert and import file values with OpenCSV
[Review] Reading and writing files with java (JDK6)
[Java] Align characters even with mixed half-width and full-width characters
Use fast Mapping library MapStruct with Lombok and Java 11
Try using DI container with Laravel and Spring Boot
Solving with Ruby and Java AtCoder ABC129 D 2D array
Summary of ToString behavior with Java and Groovy annotations
Compile with Java 6 and test with Java 11 while running Maven on Java 8
Solving with Ruby, Perl and Java AtCoder ABC 128 C
[Java basics] Let's make a triangle with a for statement
[Java] Refer to and set private variables with reflection
[LeJOS] Let's remotely control the EV3 motor with Java
I want to transition screens with kotlin and java!