


The principles and basic knowledge of WebSocket to implement Java background message push
1. What is WebSocket
The WebSocket protocol is a new network protocol based on TCP. It implements full-duplex communication between the browser and the server - allowing the server to proactively send information to the client.
2. Implementation Principle
In the process of implementing websocket connection, a websocket connection request needs to be sent through the browser, and then the server sends a response. This process is usually called "handshake". In the WebSocket API, the browser and the server only need to perform a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.
3. Advantages
In the previous message push mechanism, Ajax polling was used, and the browser automatically issued a request at a specific time interval. The server's messages are actively pulled back. This method consumes a lot of resources because it is essentially an HTTP request and is very clumsy. WebSocket completes a handshake between the browser and the server. After the connection is established, the server can actively transmit data to the client, and the client can also send data to the server at any time.
4.The difference between WebSocket and Socket
1.WebSocket:
- ##The establishment phase of websocket communication relies on the http protocol. The initial handshake phase is the http protocol. After the handshake is completed, it switches to the websocket protocol and is completely separated from the http protocol.
-
When establishing communication, the client actively initiates a connection request and the server passively listens.
Once the communication connection is established, the communication is in "full-duplex" mode. In other words, both the server and the client can send data freely at any time, which is very suitable for business scenarios where the server wants to actively push real-time data. -
The interaction mode is no longer the "request-response" mode, and the communication protocol is completely designed by the developer.
The communication data is based on "frame", which can transmit text data or binary data directly, with high efficiency. Of course, developers also have to consider technical details such as packaging, unpacking, and numbering.
2.Socket:- The server monitors communication and passively provides services; the client actively initiates a connection request to the server, Communication is established.
-
Every interaction is: the client actively initiates a request (request), and the server passively responds (response).
The server cannot actively push data to the client. -
#The communication data is based on text format. Binary data (such as pictures, etc.) must be converted into text using base64 and other means before it can be transmitted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
var websocket = var host = document.location.host; var username = //Determine whether the current browser supports WebSocket if } }
|
6. WebSocket server (java background):
1. Core class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
System.out.println( "已连接" );
clients.remove(username);
<p><code> subOnlineCount();
JSONObject jsonTo = JSONObject.fromObject(message);
<p><code> String mes = (String) jsonTo.get( "message" );
<p><code>
<p><code> if (!jsonTo.get( "To" ).equals( "All" )){
<p><code> sendMessageTo(mes, jsonTo.get( "To" ).toString());
<p><code> } else {
<p><code> sendMessageAll( "给所有人" );
<p><code> }
error.printStackTrace();
// session.getBasicRemote().sendText(message);
<p><code> //session.getAsyncRemote().sendText(message);
<p><code> for (WebSocket item : clients.values()) {
<p><code> if (item.username.equals(To) )
<p><code> item.session.getAsyncRemote().sendText(message);
<p><code> }
for (WebSocket item : clients.values()) {
<p><code> item.session.getAsyncRemote().sendText(message);
<p><code> }
return onlineCount;
WebSocket.onlineCount ;
WebSocket.onlineCount--;
return clients;
|
2.在自己代码中的调用:
1 2 3 4 5 |
|
7.所需maven依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
相关视频:
The above is the detailed content of The principles and basic knowledge of WebSocket to implement Java background message push. For more information, please follow other related articles on the PHP Chinese website!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
