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:
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.3.5</version> </dependency>
The Java code is as follows:
import java.net.URI; 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()) { @Override public void onOpen(ServerHandshake arg0) { logger.debug("Start building links..."); } @Override 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. } @Override public void onError(Exception arg0) { arg0.printStackTrace(); logger.debug("Client Error,Closing soon!"); } @Override public void onClose(int arg0, String arg1, boolean arg2) { logger.debug("Client is closed!"); logger.debug("Start trying to reconnect..."); try { Client.createConnect(); } catch (Exception e) { e.printStackTrace(); 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(); } }; client.connect(); //Judging the connection status, while (client.getReadyState().equals(READYSTATE.OPEN)) { logger.debug("Successful Link Establishment!"); } } public static void send(String message) { client.send(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
http://coolaf.com/tool/chattest
http://www.blue-zero.com/WebSocket/