SoFunction
Updated on 2025-04-23

Tutorial for implementing Java connection WebSocket

Getting started with Java Connection WebSocket

1. Introduction to WebSocket

WebSocket is a full-duplex communication protocol that allows persistent connections between clients and servers to achieve low latency, real-time interaction. Compared with traditional HTTP polling, WebSocket has higher efficiency and lower bandwidth consumption.

2. Java WebSocket Dependencies

In Java, we can useorSpring WebSocketto implement WebSocket connection.

2.1 Adding Maven dependencies

  • For Java EE WebSocket:
<dependency>
    <groupId></groupId>
    <artifactId>-api</artifactId>
    <version>1.1</version>
</dependency>
  • For Spring WebSocket:
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

3. Java WebSocket server-side implementation

3.1 Implementing a WebSocket Server with Java EE

import .*;
import ;
import ;
import ;

@ServerEndpoint("/websocket")
public class WebSocketServer {
    private static final CopyOnWriteArraySet&lt;Session&gt; sessions = new CopyOnWriteArraySet&lt;&gt;();
    
    @OnOpen
    public void onOpen(Session session) {
        (session);
        ("New connection creation: " + ());
    }
    
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        ("Received message: " + message);
        for (Session s : sessions) {
            ().sendText("Server Response: " + message);
        }
    }
    
    @OnClose
    public void onClose(Session session) {
        (session);
        ("Connection Close: " + ());
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        ();
    }
}

3.2 Configuring the WebSocket Server

If you are using Spring Boot, you need to create a WebSocket configuration class:

import ;
import ;
import ;
import ;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        (new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}

4. Java WebSocket Client Implementation

useMake a client connection:

import ;
import ;
import ;
import ;

public class WebSocketClient {
    public static void main(String[] args) {
        HttpClient client = ();
        WebSocket webSocket = ()
            .buildAsync(("ws://localhost:8080/websocket"), new WebSocketListener())
            .join();
        ("Hello WebSocket!", true);
    }
}

class WebSocketListener implements  {
    @Override
    public void onOpen(WebSocket webSocket) {
        ("WebSocket connection is successful");
        (1);
    }

    @Override
    public CompletionStage&lt;?&gt; onText(WebSocket webSocket, CharSequence data, boolean last) {
        ("Received message: " + data);
        (1);
        return null;
    }
}

5. Test WebSocket connection

  1. Start the Java WebSocket server.
  2. Run the WebSocket client to check if the connection is successful and send/receive messages.
  3. You can also use WebSocket online testing tools (e.g.) conduct the test.

Summarize

Through this article, you have learned how to connect to WebSocket using Java, including server-side and client-side implementations.

WebSocket is suitable for real-time communication scenarios, such as chat applications, data push, etc., improving the efficiency and interactive experience of network communication.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.