Java Web Sockets With Swing Client

Revella Brijesh
4 min readMay 31, 2023

Realtime Client Communication Using Swing Interface

In this blog post, we’re going to cover how to use Web Sockets to create real-time client communication using swing application. But first, let us understand how Web Sockets work.

Traditional HTTP Communication vs WebSocket Communication

As we can see in HTTP communication, once the Client receives a response from the Server the connection gets terminated. But in case of a WebSocket, once the connection opens the Client and Server can communicate with each other in real-time with multiple request and response un-till the connection is closed.

Creating Your First Java Web-Socket Project

First, we require a library to assist us creating the project. We are going to use Eclipse Tyrus — Eclipse Tyrus is an open source(API) implementation for easy development of WebSocket applications. It is a lightweight, scalable, and portable WebSocket implementation that allows Java applications to establish two-way communication with clients over a WebSocket connection.

Add the following dependencies to your Project[Maven,Gradle,Ivy,SBT]:

  1. tyrus.server
  2. tyrus.client
  3. tyrus.container.grizzly

After setting up your project, let us move forward with the coding part.

Server Code

To host a server, we need to perform the following steps:

  1. First we need to import the package org.glassfish.tyrus.server. Using this package we can use the Server class.
  2. To create Server class object, We need to pass parameters to the Server class Constructor.

localhost is the Hostname.

8026 is the port number.

/folder is the root path for the server app.

ChatServerEndpoint.class returns the Class Class object, using which the serverdemo class can dynamically get the metadata of the ChatServerEndpoint.class using which server class can execute all the methods of the class.

3. To start the server, we can use the server start() method.

Product

Product class is a model for transferring the data.

We only write getters and setters for the variables pid, pname, price.

ChatServerEndpoint

The @ServerEndpoint annotation marks this class as a WebSocket server endpoint. The value attribute specifies the endpoint URL ("/app" in this case).

The encoders and decoders attributes specify the classes responsible for encoding outgoing messages and decoding incoming messages, respectively.

  1. The onOpen method is executed when a new WebSocket connection is established. getId() method returns the current sessionId.

2. The onMessage method, is called when a message is received from a client. It takes two parameters(Product object representing the message and Session object representing the connection). The getOpenSessions() iterates over all the open sessions and the getBasicRemote().sendObject() method sends the received message to all the connected clients.

3.The onClose method is executed when a WebSocket connection is closed. It receives the Session object and a CloseReason object indicating the reason for the closure.

MessageEncoder

In WebSocket communication, the data exchange occurs in the form of messages between the client and server. When it comes to sending complex objects, such as Java objects, over a WebSocket connection, an encoder and decoder are used to convert these objects into a suitable format that can be transmitted as text or binary data and then reconstructed on the receiving end.

This code represents an implementation of the Encoder.Text interface for encoding Product object into JSON string to be sent over a WebSocket connection.

MessageDecoder

This code represents an implementation of the Decoder.Text interface for decoding JSON string to Product object received over a WebSocket connection.

ChatClientEndpoint

This code creates a simple GUI application for connecting to a WebSocket server and sending/receiving messages. The ChatClientEndpoint class is annotated with @ClientEndpoint to specify that it represents a WebSocket client endpoint.

The connectToWebSocket() method initializes the WebSocket connection. It creates a ChatClientEndpoint instance, sets up a message listener, and connects to the specified URI.

  1. The onOpen method is invoked when the WebSocket connection is established. It sends a "start" message to the server.
  2. The onMessage method is invoked when a message is received from the server. It calls the actionPerformed method of the registered MessageListener to handle the received message.
  3. The onClose method is invoked when the WebSocket connection is closed. It logs the reason for closure and decrements the latch.
  4. The addMessageListener method in ChatClientEndpoint allows registering a MessageListener to handle received messages.

Source Code

The complete source code for the described example is available on my GitHub. Explore the details there and happy coding.

--

--