[JAVA] Try WebSocket with jooby

Try WebSocket communication with jooby.

Prerequisites

--jooby's QUICK START has ended

① Preparation of HTML for client

Place ws.html directly under the public directory.

ws.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket sample</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
    var ws = new WebSocket("ws://localhost:8080/ws");
    ws.onmessage = function(message){
        $("#log").prepend(message.data + "<br>");
    }
    $("#message").keyup(function(e){
        ws.send($(this).val());
    });
})
</script>
</head>
<body><input type="text" id="message"><div id="log"></div></body>
</html>

(2) Addition of processing on the server side

It is a simple configuration that receives a message, returns it to the sender, and broadcasts it.

App.java


	{
		assets("/ws.html", "ws.html");
		ws("/ws", ws -> {
			ws.onMessage(msg -> {
				ws.send("send : " + msg.value());
				ws.broadcast("broadcast : " + msg.value());
			});
		});
	}

③ Access ** http: //localhost:8080/ws.html ** from a browser on multiple tabs and enter a message in the text box.

In each tab, both the message I sent and the broadcast are displayed, so it seems to be working properly.

Tab 1

image.png

Tab 2

image.png

Finally

I think that it is very easy and easy to understand because simple ** WebSocket ** communication is possible with only this amount of description. However, if you are familiar with Java for a long time, it doesn't look like Java code.

Recommended Posts

Try WebSocket with jooby
Let's try WebSocket with Java and javascript!
Try DI with Micronaut
Try WildFly with Docker
Run Mosquitto with Docker and try WebSocket communication with MQTT
Try using GloVe with Deeplearning4j
Try using view_component with rails
Try DB connection with Java
Try gRPC with Java, Maven
Try reading XML with JDOM
Try running cloudera manager with docker
Try implementing recaptcha with Jetty embedded.
Try manipulating PostgreSQL arrays with JDBC
Try using Redis with Java (jar)
Try to imitate marshmallows with MiniMagick
Build jooby development environment with Eclipse
Try parsing English with Stanford CoreNLP
Try bidirectional communication with gRPC Java
Try running MySql and Blazor with docker-compose
Try running Slack's (Classic) Bot with docker
Try using Spring Boot with VS Code
Try shaking your hands with ARKit + Metal
Try to implement login function with Spring-Boot
Try managing Java libraries with AWS CodeArtifact
Try using Kong + Konga with Docker Compose.
Try with resources statement in web app
Try using the Wii remote with Java
Try creating an iOS library with CocoaPods