Socket communication with a web browser using Java and JavaScript ②

background

Past articles: https://qiita.com/take4eng/items/d0b009c48ee8c3fe420a

As described in the previous article above, create a server program in Java and perform socket communication. ⇒Since HTTP communication is analyzed by pushing it, the code is uselessly complicated.

There are many APIs related to socket communication in Java EE, and it is very easy to implement. Many people have already summarized it, but I will summarize the implementation contents.

Even though a convenient API is prepared, no one does analysis by pushing it. Even if I google it, it doesn't come out easily ...

Practical content

  1. How to use WebSocket API
  2. Create a server program using the API
  3. Edit the client program code in the past article to create a chat application

How to use WebSocket API

Describes the basic WebSocket API. There are many APIs other than those introduced here, but you can google if necessary.

Creating an Endpoint class

import javax.websocket.server.ServerEndpoint;
 
@ServerEndpoint("/Context path")
public class SanpleEndpoint {
}
  1. Import the ServerEndpoint class
  2. Annotate the class with @ServerEndpoint
  3. Write a context path that indicates the location of the file

Creating a processing method

/*
Import each class
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
*/

//Processing when connecting to a client
@OnOpen
public void onOpen(Session session) {
}
 
//What to do when a message is received from a client
@OnMessage
public void onMessage(String message) {
}

//What to do when an error occurs
@OnError
public void onError(Throwable error) {
}

//What to do when the connection with the client is lost
@OnClose
public void onClose(Session session) {
}
  1. Import the required classes
  2. Add each annotation corresponding to the method
  3. Arguments can be changed or added as needed

Create a server program using API

Server program


import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

//Annotation that indicates that it is a server-side class of WebSocket.
//argument(wSck)Represents the URI used when connecting from the client.
@ServerEndpoint(value = "/wSck")
public class SocketFree2 {

	//Create a client session thread(Save each session for each client)
	//Set: Collection with no duplicate elements
	//CopyOnWriteArrayList:java.util.A thread-safe version of Set
	private static Set<Session> user = new CopyOnWriteArraySet<>();

	@OnOpen//When connecting with a client
    public void onOpen(Session mySession) {
        System.out.println("connect ID:"+mySession.getId());//session.getId():Get session ID
        user.add(mySession);//Add session for each client to list
    }

    @OnMessage//When data is sent from the client
    public void onMessage(String text , Session mySession) {//The arguments are the text sent and the session from which it originated.
    	System.out.println(text);
    	//getAsyncRemote(): Get an instance of RemoteEndpoint
    	//sendText(String): Send text to client
    	for (Session user : user) {
    		user.getAsyncRemote().sendText(text);
            System.out.println(user.getId()+"Second"+mySession.getId()+"I sent the second message!");
    	}
    	if(text.equals("bye")) onClose(mySession);//Disconnect if text is "bye"
    }

    @OnClose//When the client disconnects
    public void onClose(Session mySession) {
    	System.out.println("disconnect ID:"+mySession.getId());
        user.remove(mySession);//Remove disconnected client session from list
        try {
			mySession.close();//Disconnect with close method
		} catch (IOException e) {
			System.err.println("An error has occurred: " + e);
		}
    }

}

Code description

    1. Add Endpoint annotation @ServerEndpoint to class and describe context path @ServerEndpoint(value = "/wSck")
  1. Create a list that identifies each client private static Set<Session> user = new CopyOnWriteArraySet<>();

    1. onOpen method: Add client session to list user.add(mySession);

Four. onMessage method: Send the received text to the client as it is ⇒ Send to all clients connected by for statement user.getAsyncRemote().sendText(text);

Five. onClose method: delete the disconnected client 5-1. Remove from user list: ʻuser.remove (mySession); 5-2. Delete session and disconnect:mySession.close ();`

Execution result

Change the address of the client program and execute it with a web browser.

image.png A chat application that displays the sent contents is completed. It also supports access from multiple browsers.

Impressions

Socket communication was very easy to do by using the API. Compared to the one described in the past article, the amount of code written is about 1/4. It's amazing. Super easy.

Besides, it seems that encoding, decoding processing and handling of json data can be done easily. I haven't used it this time, but it will be necessary for full-scale development. See the reference page for details.

Reference page

Recommended Posts

Socket communication with a web browser using Java and JavaScript ②
Socket communication with a web browser using Java and JavaScript ①
Create a high-performance enum with fields and methods like Java with JavaScript
Let's try WebSocket with Java and javascript!
Java and JavaScript
Graph the sensor information of Raspberry Pi in Java and check it with a web browser
Prepare a scraping environment with Docker and Java
Create a portfolio app using Java and Spring Boot
How to convert A to a and a to A using AND and OR in Java
Create a JAVA WEB application and try OMC APM
[Java] Development with multiple files using package and import
[Java] JSON communication with jackson
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Using Mapper with Java (Spring)
Problems with Dijkstra's algorithm using PriorityQueue and adjacency list (java)
Try developing a containerized Java web application with Eclipse + Codewind
Create a Java and JavaScript team development environment (gradle environment construction)
A Simple CRUD Sample Using Java Servlet / JSP and MySQL
Make a rhombus using Java
AWS Elastic Beanstalk # 1 with Java starting from scratch-Building a Java web application environment using the EB CLI-
Let's make a LAN communication application Part 1 New project creation using Maven and Java entry point
Create a simple web server with the Java standard library com.sun.net.httpserver
Comparison of WEB application development with Rails and Java Servlet + JSP
Automatically deploy a Web application developed in Java using Jenkins [Preparation]
Memorandum No.2 "Making a search history with ArrayList and HashSet" [Java]
Build a Java project with Gradle
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Install Java and Tomcat with Ansible
Upload a file using Java HttpURLConnection
Use JDBC with Java and Scala.
Try using Redis with Java (jar)
Build a web application with Javalin
I tried UDP communication with Java
Create a Java project using Eclipse
Output PDF and TIFF with Java 8
Using Java with AWS Lambda-Eclipse Preparation
Html5 development with Java using TeaVM
Try bidirectional communication with gRPC Java
Using proxy service with Java crawling
Encrypt with Java and decrypt with C #
Process Communication using AMQP with RabbitMQ
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method
Build a web application development environment that uses Java, MySQL, and Redis with Docker CE for Windows
A collection of phrases that impresses the "different feeling" of Java and JavaScript
Creating a project (and GitHub repository) using Java and Gradle in IntelliJ IDEA
Beginners create web applications with Java and MySQL (adding at any time)
[Java] Create a jar file with both compressed and uncompressed with the jar command
Creating a java web application development environment with docker for mac part1
Java beginner tried to make a simple web application using Spring Boot
Automatically deploy a web application developed in Java using Jenkins [Spring Boot application]
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I wrote a Lambda function in Java and deployed it with SAM
<java> Split the address before and after the street address with a regular expression
Create a java web application development environment with docker for mac part2
How to make an app with a plugin mechanism [C # and Java]
[Java] I installed JDBC and tried to connect with servlet + MySQL. (There is a version using DAO / Bean)
[Java] Create and apply a slide master
Create a web environment quickly using Docker
Try using Java framework Nablarch [Web application]