1. What is websocket
WebSocket is a protocol that implements real-time two-way communication in web applications. It provides a persistent connection between the browser and the server, where data can be transferred in both directions on one connection. Compared with the traditional HTTP protocol, WebSocket has lower latency and higher efficiency.
WebSocket uses a handshake method similar to a handshake to establish a connection. During the handshake process, the browser and the server will exchange some information to establish a WebSocket connection. Once the connection is established, data can be transferred between the browser and the server in real time without the need to initiate a new HTTP request every time.
The WebSocket protocol can be implemented in different platforms and programming languages, including web browsers and server-side. In a web browser, you can use the WebSocket API in JavaScript to implement WebSocket connections. On the server side, various programming languages and frameworks can be used to implement WebSocket servers.
WebSocket has a wide range of application scenarios. It can be used for real-time chat applications, real-time games, real-time stock quotes, real-time collaborative editing and other applications that require real-time communication. Through WebSocket, developers can more easily implement real-time communication functions and improve user experience.
Here we use Java with springboot2.
2. Depend on coordinate address
Parent dependency
<!--Relying on parent project--> <parent> <groupId></groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> </parent>
rely
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
rely
<dependency> <groupId>-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.3.8</version> </dependency>
3. Code
I won’t say much, just take it and read it, it’s all in the comments.
server:
package ; import ; import org.java_websocket.WebSocket; import org.java_websocket.; import org.java_websocket.; import org.; import org.; import ; import ; import ; import ; import ; import ; @Component public class P2pPointServer { //Log Recording private Logger logger = (); //Native Server's WebSocket port private Integer port = 7001; //All WebSocket caches connected to the server private List<WebSocket> localSockets = new ArrayList<>(); public List<WebSocket> getLocalSockets() { return localSockets; } public void setLocalSockets(List<WebSocket> localSockets) { = localSockets; } @PostConstruct @Order(1) public void initServer(){ final WebSocketServer socketServer = new WebSocketServer(new InetSocketAddress(port)) { // Triggered when the link is created successfully @Override public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { sendMessage(webSocket,"I'm back, kids!"); (webSocket); } // Triggered when disconnected @Override public void onClose(WebSocket webSocket, int i, String s, boolean b) { (() + "Client disconnected from server"); (webSocket); } //Triggered when a message is received @Override public void onMessage(WebSocket webSocket, String s) { ("Received the message from the client:" + s); sendMessage(webSocket,"I've heard from kids"); } //Called when the connection is sent error, and then the onClose method is triggered @Override public void onError(WebSocket webSocket, Exception e) { (() + "Client and server connection send error"); (webSocket); } @Override public void onStart() { ("I'm going to start, kids!!"); } }; (); ("Man! what can I say, I've started"); } /** * One-to-one send * @param webSocket: Client * @param message: information */ public void sendMessage(WebSocket webSocket,String message){ ("Send to"+().getPort() + "The p2p message is:" + message); (message); } /** * One-to-many send * @param message: information */ public void broatcast(String message){ if (() == 0 || (message)) return; ("Open the third eye"); for (WebSocket webSocket : localSockets){ (webSocket,message); } ("I'm burning out the kids"); } }
Client:
package ; import ; import org.java_websocket.WebSocket; import org.java_websocket.; import org.java_websocket.; import org.; import org.; import ; import ; import ; import ; import ; import ; @Component public class P2pPointClient { //Log Recording private Logger logger = (); //The address of the server private String wsUrl = "ws://localhost:7001/"; //All WebSocket caches connected to the client private List<WebSocket> localSockets = new ArrayList<>(); public List<WebSocket> getLocalSockets() { return localSockets; } public void setLocalSockets(List<WebSocket> localSockets) { = localSockets; } @PostConstruct @Order(2) public void connectServer(){ try { final WebSocketClient socketClient = new WebSocketClient(new URI(wsUrl)) { @Override public void onOpen(ServerHandshake serverHandshake) { sendMessage(this,"Kids, I'm a client"); (this); } @Override public void onMessage(String s) { ("Received a message from the server:"+s); } @Override public void onClose(int i, String s, boolean b) { ("Disconnect"); (this); } @Override public void onError(Exception e) { ("Connection Error"); (this); } }; (); } catch (Exception e) { (); ("Connection Error"); } } /** * One-to-one send * @param webSocket: Client * @param message: information */ public void sendMessage(WebSocket webSocket,String message){ ("Send to"+().getPort() + "The p2p message is:" + message); (message); } /** * One-to-many send * @param message: information */ public void broatcast(String message){ if (() == 0 || (message)) return; ("Open the third eye"); for (WebSocket webSocket : localSockets){ (webSocket,message); } ("I'm burning out the kids"); } }
Summarize
This is the end of this article about Java springBoot's preliminary use of websocket. For more related content about springBoot's use of websocket, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!