Java Server Establishes Long Links as Web Socket Client

Keywords: Java socket xml Apache

In recent projects, web socket communication between Java server and c++ is needed. The plug-in of java_websocket.client.WebSocketClient solves this requirement well.

First, you need to introduce this dependency in the pom.xml file:


The Java code is as follows:


import org.apache.log4j.Logger;
import org.java_websocket.WebSocket.READYSTATE;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import common.constant.SystemConstant;
import logic.zhuoyue.receive.ReceiveInterval;
import logic.zhuoyue.send.thread.SendHeartThread;
import logic.zhuoyue.send.thread.SendInThread;
import logic.zhuoyue.send.thread.SendMonthCardThread;
import logic.zhuoyue.send.thread.SendOutThread;
 * Establish a connection...
 * send data
 * @author apple
public class Client {
	private final static Logger logger = Logger.getLogger(Client.class);

	public static  WebSocketClient client;

	public static void createConnect() throws Exception{

             //SystemConstant.WS_URL: WS URL address

		client = new WebSocketClient(new URI(SystemConstant.WS_URL), new Draft_6455()) {
			public void onOpen(ServerHandshake arg0) {
				logger.debug("Start building links...");

			public void onMessage(String arg0) {
				logger.debug("Server request detected...");
				//This method automatically receives information from the server and calls the method written by itself directly here.

			public void onError(Exception arg0) {
				logger.debug("Client Error,Closing soon!");

			public void onClose(int arg0, String arg1, boolean arg2) {
				logger.debug("Client is closed!");
				logger.debug("Start trying to reconnect...");
				try {
				} catch (Exception e) {
					logger.debug("Reconnection failed,Please check the network!");
				//Create 4 Timing Task Threads after Restarting the Client
				new SendHeartThread().start();
				new SendInThread().start();
				new SendOutThread().start();
				new SendMonthCardThread().start();

		//Judging the connection status,
		while (client.getReadyState().equals(READYSTATE.OPEN)) {
			logger.debug("Successful Link Establishment!");

	public static void send(String message) {

2. When we need to send information to the server
Client client instance can be treated as a tool class operation directly.

For example: Client.send("message sent");

3. When we need to receive information from the server
Receive it directly in the onMessage method in the Client class and process it yourself.

4. Online websocket server test address

Posted by turpentyne on Mon, 30 Sep 2019 09:04:38 -0700