Code ví dụ Java SocketCluster Client, publish và subscribe channel

Code ví dụ Java SocketCluster Client, publish và subscribe channel

Trong bài này mình sẽ thực hiện tạo channel và listen channel socket cluster bằng Java.

Tạo và start SocketCluster server

Đầu tiên mình tạo và chạy SocketCluster Server ỏ port 8000

  • Tạo server socketcluster với tên là SocketClusterServer
socketcluster create SocketClusterServer
  • Start server socketcluster vừa tạo:
node server.js

Di chuyển tới tới folder SocketClusterServer và start SocketCluster server

 Code ví dụ Java SocketCluster Client

Tạo Maven Project

Thư viện sử dụng

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>SocketClusterClient</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

  <repositories>
    <repository>
      <id>my-repo1</id>
      <name>socketcluster</name>
      <url>http://repo.spring.io/plugins-release</url>
    </repository>
  </repositories>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/io.github.sac/SocketclusterClientJava -->
    <dependency>
      <groupId>io.github.sac</groupId>
      <artifactId>SocketclusterClientJava</artifactId>
      <version>1.7.4</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
    </dependency>
  </dependencies>

</project>

Tạo client thực hiện kết nối tới server socketcluster để subscribe channel và publish data tới channel.

package socketclusterclient;

import java.text.SimpleDateFormat;
import java.util.*;
import com.neovisionaries.ws.client.*;
import io.github.sac.*;

public class KaiClient {
  public static void main(String[] args) throws Exception {
    // Create a socket instance
    String url = "ws://localhost:8000/socketcluster/";

    Socket socket = new Socket(url);
    socket.setListener(new BasicListener() {

      public void onConnected(Socket socket, Map<String, List<String>> headers) {
        System.out.println("Connected to endpoint");
      }

      public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
          boolean closedByServer) {
        System.out.println("Disconnected from end-point");
      }

      public void onConnectError(Socket socket, WebSocketException exception) {
        System.out.println("Got connect error " + exception);
      }

      public void onSetAuthToken(String token, Socket socket) {
        System.out.println("Token is " + token);
      }

      @Override
      public void onAuthentication(Socket socket, Boolean status) {
      }
    });

    // By default logging of messages is enabled ,to disable
    socket.disableLogging();
    // This will set automatic-reconnection to server with delay of 2
    // seconds and repeating it for 30 times
    socket.setReconnection(new ReconnectStrategy().setDelay(2000).setMaxAttempts(30));
    // This will send websocket handshake request to socketcluster-server
    socket.connect();

    Socket.Channel channel = socket.createChannel("kai");
    channel.subscribe(new Ack() {
      public void call(String channelName, Object error, Object data) {
        if (error == null) {
          System.out.println("Listen channel kai: " + data);
        }
      }
    });

    channel.onMessage(new Emitter.Listener() {
      public void call(String channelName, Object object) {
        System.out.println("Message from channel " + channelName + ": " + object.toString());
      }
    });

    Thread t = new Thread(new Runnable() {

      @Override
      public void run() {
        while (true) {
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
          }
          socket.publish("sena", "kai - " + new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date()));
        }
      }
    });
    t.start();
  }
}

Trong đoạn code trên mình thực hiện:

  • Kết nối với server socket cluster ở địa chỉ localhost:8000
  • subscribe channel ‘kai‘ (ai muốn chat với kai thì publish message vào channel này)
  • cứ 5s thì publish message tới channel sena (kai thực hiện gửi message cho sena).

Tương tự mình tạo một client khác là SenaClient thực hiện nhận message từ channel ‘sena‘ và gửi message tới channel ‘kai

package socketclusterclient;

import java.text.SimpleDateFormat;
import java.util.*;
import com.neovisionaries.ws.client.*;
import io.github.sac.*;

public class SenaClient {
  public static void main(String[] args) throws Exception {
    // Create a socket instance
    String url = "ws://localhost:8000/socketcluster/";

    Socket socket = new Socket(url);
    socket.setListener(new BasicListener() {

      public void onConnected(Socket socket, Map<String, List<String>> headers) {
        System.out.println("Connected to endpoint");
      }

      public void onDisconnected(Socket socket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
          boolean closedByServer) {
        System.out.println("Disconnected from end-point");
      }

      public void onConnectError(Socket socket, WebSocketException exception) {
        System.out.println("Got connect error " + exception);
      }

      public void onSetAuthToken(String token, Socket socket) {
        System.out.println("Token is " + token);
      }

      @Override
      public void onAuthentication(Socket socket, Boolean status) {
      }
    });

    // By default logging of messages is enabled ,to disable
    socket.disableLogging();
    // This will set automatic-reconnection to server with delay of 2
    // seconds and repeating it for 30 times
    socket.setReconnection(new ReconnectStrategy().setDelay(2000).setMaxAttempts(30));
    // This will send websocket handshake request to socketcluster-server
    socket.connect();

    Socket.Channel channel = socket.createChannel("sena");
    channel.subscribe(new Ack() {
      public void call(String channelName, Object error, Object data) {
        if (error == null) {
          System.out.println("Listen channel sena: " + data);
        }
      }
    });

    channel.onMessage(new Emitter.Listener() {
      public void call(String channelName, Object object) {
        System.out.println("Message from channel " + channelName + ": " + object.toString());
      }
    });
    Thread t = new Thread(new Runnable() {
      
      @Override
      public void run() {
        while(true){
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
          }
          socket.publish("kai", "sena - " + new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date()));
        }
      }
    });
    t.start();
  }
}

Demo

Chạy file KaiClient.java sau đấy chạy file SenaClient.java

Code ví dụ Java SocketCluster Client, publish và subscribe channel

 

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://github.com/sacOO7/socketcluster-client-java

stackjava.com