[Java EE] Implement Client with WebSocket

Recently, the Qiita article has become a progress report. This time, it is a continuation of the article here.

Addition of tyrus-standalone-client

When I write and execute a client program normally, I get the following error.

Exception in thread "main" java.lang.RuntimeException: Could not find an implementation class.
	at javax.websocket.ContainerProvider.getWebSocketContainer(ContainerProvider.java:73)
	at Main.main(Main.java:46)

According to stackoverrun, websocket provides a Client interface, but doesn't seem to provide an implementation. Therefore, we will introduce tyrus-standalone-client in glassfish. How to implement WebSocketContainer in StandardWebSocketClient class

Specifically, add it to the dependencies of build.gradle.

dependencies {
    //I explained last time
    compileOnly 'javax:javaee-api:8.0'
    //This is what I will add this time
    compile group: 'org.glassfish.tyrus.bundles', name: 'tyrus-standalone-client', version: '1.14'
}

Write ClientEndPoint

So, let's write a program this time. -> src-> main-> Create a .java file in (appropriate package) in java.


import javax.websocket.*;
import java.net.URI;
import java.util.Scanner;

//With this annotation, it is recognized as the endpoint of the client.
@ClientEndpoint
public class Client {

    public Client() {
        super();
    }

    //Processing when establishing a session
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("[Session establishment]");
    }

    //Processing when receiving a message
    @OnMessage
    public void onMessage(String message) {
        System.out.println("[Receive]:" + message);
    }

    //Processing when receiving a message
    @OnError
    public void onError(Throwable th) {
        System.err.println(th.getMessage());
    }

    //Processing at session release
    @OnClose
    public void onClose(Session session) {
        System.out.println("[Disconnect]");
    }

    static public void main(String[] args) throws Exception {

        //Get the object of WebSocket container for initialization
        WebSocketContainer container = ContainerProvider
                .getWebSocketContainer();
        //Server endpoint URI
        URI uri = URI
                .create("ws://localhost:8080/<Project name>/<Link>");
        //Establish a session with the server endpoint
        //From the running client, look for the same class passed as an argument and connect?
        Session session = container.connectToServer(Client.class, uri);

        while (!session.isOpen()) {
            Thread.sleep(500);
        }

        System.out.println("open");

        try (Scanner s = new Scanner(System.in)) {
            String str;
            System.out.println("start loop");
            while (true) {
                str = s.nextLine();
                if(str.equals("exit")) break;
                //Send the contents of str
                session.getBasicRemote().sendText(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Since it is troublesome, I wrote main in the Endpoint class this time, but I feel that it is better to separate it.

Run

First, start the server containing Client with tomcatRun etc., and then execute main in another window.

Recommended Posts

[Java EE] Implement Client with WebSocket
Enable Java EE with NetBeans 9
API integration from Java with Jersey Client
One-JAR Java EE application with WebSphere Liberty
Java EE test (CDI / interceptor) with Arquillian
Let's try WebSocket with Java and javascript!
Java mqtt client
Build an E2E test environment with Selenium (Java)
Try to implement TCP / IP + NIO with JAVA
I tried to implement TCP / IP + BIO with JAVA
Change seats with java
Install Java with Ansible
Try WebSocket with jooby
Comfortable download with JAVA
Switch java with direnv
Quickly implement a singleton with an enum in Java
Implement API client with only annotations using Feign (OpenFeign)
I tried to implement Stalin sort with Java Collector
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Serverless Java EE starting with Quarkus and Cloud Run
Endian conversion with JAVA
I tried to modernize a Java EE application with OpenShift.
This is all you need WebSocket: Server = Java, Client = Java, JavaScript
I want to implement various functions with kotlin and java!
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Play with Jersey OAuth 2 client
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Implement GraphQL with Spring Boot
Java to play with Function
GraphQL Client starting with Ruby
Try DB connection with Java
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Implement two-step verification in Java
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
Implement Basic authentication in Java
Implement jCaptcha reload with ajax
[Java] Content acquisition with HttpCliient
Java version control with jenv
Implement math combinations in Java
Troubleshooting with Java Flight Recorder
Streamline Java testing with Spock
2 Implement simple parsing in Java
Connect to DB with Java