WebSocket
Ask customer service to test the domain name
Step 1: Send key after connecting: your key: country id
Sending example: ws.send("key:your key:14") If the authentication is successful, it will return the string "Authentication Success"
Step 2: Send a heartbeat every 10 seconds
Send example: ws.send("heartbeat") After the heartbeat is sent successfully, the pong string will be returned
DEMO
java
// Below is the sample code and package version
// <dependencies>
// <dependency>
// <groupId>org.java-websocket</groupId>
// <artifactId>Java-WebSocket</artifactId>
// <version>1.3.5</version>
// </dependency>
// <dependency>
// <groupId>org.json</groupId>
// <artifactId>json</artifactId>
// <version>20220924</version>
// </dependency>
// </dependencies>
package com.client;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
public class WebSocketClientExample {
public static void main(String[] args) {
try {
URI uri = new URI("ws://ws.com"); // Replace with the actual WebSocket address
String key = "key:Your key:Country ID"; // Replace with actual key and country id
WebSocketClient client = new WebSocketClient(uri) {
private Timer heartbeatTimer;
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server");
send(key);
// Start the heartbeat timer
heartbeatTimer = new Timer();
heartbeatTimer.schedule(new TimerTask() {
@Override
public void run() {
send("heartbeat");
}
}, 0, 3000); // Send a heartbeat message every 3 seconds
}
@Override
public void onMessage(String message) {
// Get the current time and format it as a string
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = now.format(formatter);
try {
if (message.contains("Authentication successful") || message.contains("pong") || message.contains("Authentication failed")) {
System.out.println(timestamp + "" + message);
return;
}
JSONObject json = new JSONObject(message);
String pid = json.optString("pid");
String last = json.optString("last");
// Output pid and last
// System.out.println(timestamp + " pid: " + pid + "price: " + last);
} catch (Exception e) {
System.err.println("An error occurred while processing the message: " + message);
}
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed: " + reason);
if (heartbeatTimer != null) {
heartbeatTimer.cancel(); // Cancel the heartbeat timer
}
// Try to reconnect
try {
System.out.println("Try to reconnect...");
Thread.sleep(10000); // Try to reconnect after 10 seconds
connect(); // Reconnect
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onError(Exception ex) {
System.err.println("An error occurred: " + ex.getMessage());
}
};
client.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
php
// Test environment: PHP 7.4.33, Composer 2.7.6
// Install the necessary dependencies using Composer
// composer require textalk/websocket
// composer require react/event-loop
// composer require react/promise
<?php
require 'vendor/autoload.php';
use WebSocket\Client;
use React\EventLoop\Factory;
use React\Promise\Deferred;
$url = "ws://test.com";
$heartbeatInterval = null; // Declare the heartbeat timer variable
$ws = null; // WebSocket client instance
function open($ws, $loop) {
global $heartbeatInterval; // Reference the global variable
try {
// Send a message containing the key for authentication
$ws->send('key:your_key:country_id');
echo "Connected to the server\n";
// Define the heartbeat timer
$heartbeatInterval = $loop->addPeriodicTimer(3, function () use ($ws) {
try {
$ws->send('heartbeat');
} catch (Exception $e) {
echo "Failed to send heartbeat: {$e->getMessage()}\n";
}
});
} catch (Exception $e) {
echo "Authentication failed: {$e->getMessage()}\n";
}
}
function reconnect($loop, $url) {
global $ws, $heartbeatInterval; // Reference global variables
if ($heartbeatInterval !== null) {
$loop->cancelTimer($heartbeatInterval); // Stop the heartbeat timer
$heartbeatInterval = null;
}
if ($ws !== null) {
try {
$ws->close(); // Attempt to close the previous connection
} catch (Exception $e) {
echo "Failed to close connection: {$e->getMessage()}\n";
}
$ws = null;
}
echo "Attempting to reconnect...\n";
$loop->addTimer(10, function () use ($loop, $url) { // Attempt to reconnect after 10 seconds
global $ws;
try {
$ws = new Client($url, ['timeout' => 10]); // Set a read timeout for the connection
open($ws, $loop); // Open the new connection
} catch (Exception $e) {
echo "Reconnection failed: {$e->getMessage()}\n";
reconnect($loop, $url); // If reconnection fails, recursively call reconnect
}
});
}
// Asynchronously process received data
function processData($message) {
$deferred = new Deferred();
// Simulate asynchronous processing; this can be any async task
$deferred->resolve("Processed data: {$message}");
return $deferred->promise();
}
$loop = Factory::create();
$ws = new Client($url, ['timeout' => 10]); // Initial connection
open($ws, $loop);
// Use ReactPHP's periodic timer to handle WebSocket messages
$loop->addPeriodicTimer(0, function () use ($loop, $url) {
global $ws, $heartbeatInterval; // Reference global variables
try {
if ($ws !== null) {
$message = $ws->receive();
if ($message !== null) {
echo "Received message from server: {$message}\n";
// Asynchronously process the received data
processData($message)->then(function ($result) {
echo "{$result}\n";
});
}
}
} catch (WebSocket\ConnectionException $e) {
echo "WebSocket connection error: {$e->getMessage()}\n";
// Specifically handle "Bad opcode" errors
if (strpos($e->getMessage(), 'Bad opcode') !== false) {
echo "Invalid opcode received, reconnecting...\n";
reconnect($loop, $url);
} else {
reconnect($loop, $url);
}
} catch (Exception $e) {
echo "An error occurred: {$e->getMessage()}\n";
// Connection lost, attempt to reconnect
reconnect($loop, $url);
}
});
// Run the event loop
$loop->run();
javascript
const WebSocket = require("ws");
let ws = new WebSocket(url);
function open() {
// Send a message containing the key for authentication
ws.send('key:your_key:country_id');
// Send a heartbeat message to keep the connection alive
console.log('Connected to the server');
heartbeatInterval = setInterval(function () {
ws.send('heartbeat');
}, 1000 * 3); // Send a heartbeat message every 3 seconds
}
ws.onopen = open;
ws.onmessage = async function (event) {
console.log('Received message from server:', event.data);
// Handle messages received from the server here
};
ws.onclose = function (e) {
clearInterval(heartbeatInterval); // Clear the heartbeat timer
// Attempt to reconnect
setTimeout(function () {
console.log('Attempting to reconnect...', e);
const newWs = new WebSocket(url);
newWs.onopen = function () {
console.log('Reconnection successful');
ws = newWs; // Update the `ws` object with the new WebSocket instance
open();
};
newWs.onmessage = ws.onmessage;
newWs.onclose = ws.onclose;
newWs.onerror = ws.onerror;
}, 1000 * 10); // Attempt to reconnect after 10 seconds
};
ws.onerror = function (error) {
console.error('An error occurred:', error);
};