Table of Contents
1. What is WebSocket
2. Implementation Principle
3. Advantages
4.The difference between WebSocket and Socket
 1.WebSocket:
6. WebSocket server (java background):
  7.所需maven依赖:
Home Java javaTutorial The principles and basic knowledge of WebSocket to implement Java background message push

The principles and basic knowledge of WebSocket to implement Java background message push

Aug 03, 2018 am 11:35 AM
websocket

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:

    1. ##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.

    2. When establishing communication, the client actively initiates a connection request and the server passively listens.

    3. 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.

    4. The interaction mode is no longer the "request-response" mode, and the communication protocol is completely designed by the developer.


    5. 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.

    6.  2.Socket:
    7. The server monitors communication and passively provides services; the client actively initiates a connection request to the server, Communication is established.

    8. Every interaction is: the client actively initiates a request (request), and the server passively responds (response).

    9. The server cannot actively push data to the client.

    10. #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.


5.WebSocket client:

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 = null;

var host = document.location.host;

var username = "${loginUsername}"; // Get the userName of the currently logged in person

// alert(username)

//Determine whether the current browser supports WebSocket

if ('WebSocket' in window) {

alert("The browser supports Websocket")

websocket = new WebSocket('ws://' host '/mm-dorado/webSocket/' username);

} else {

alert('Current browser Not support websocket')

}

//Callback method for connection errors

websocket.onerror = function() {

 alert("WebSocket connection error")

setMessageInnerHTML("WebSocket connection error");

};

//Callback method for successful connection establishment

websocket.onopen = function() {

 alert("WebSocket connection successful")

setMessageInnerHTML("WebSocket connection successful");

}

//Callback method for receiving message

websocket.onmessage = function(event) {

alert("Callback method of receiving message")

alert("This is the message pushed in the background:" event.data);

websocket.close();

  alert("webSocket has been closed!")

}

//Callback method for connection closing

websocket.onclose = function() {

setMessageInnerHTML("WebSocket connection closed");

}

//Listen to the window closing event. When the window is closed, actively close the websocket connection to prevent the window from closing before the connection is disconnected. The server will throw an exception.

window.onbeforeunload = function() {

closeWebSocket();

}

//Close WebSocket connection

function closeWebSocket() {

websocket.close();

}

//Display the message on the web page

function setMessageInnerHTML(innerHTML) {

       document.getElementById('message').innerHTML = innerHTML '<br/>' ;

}

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

package com.mes.util;

import java.io.IOException;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;

import javax.websocket.OnError;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

import com.google.gson.JsonObject;

import net.sf.json.JSONObject;

@ServerEndpoint("/webSocket/{username}")

public class WebSocket {

       private static int onlineCount = 0;

       private static Map<String, WebSocket> clients = new ConcurrentHashMap<String , WebSocket>();

        private Session session;

        private String username;

<p><code>                                                                    

       

@OnOpen

     

public void onOpen(@PathParam(" username") String username, Session session) throws IOException {

       

 

            

this.username = username;

          

this.session = session;

                                                                  

         

addOnlineCount();

<p><code>            clients.put(username, this);

<p><code>            System.out.println("已连接");

        

       

        @OnClose 

        public void onClose() throws IOException { 

<p><code>            clients.remove(username); 

<p><code>            subOnlineCount(); 

        

       

        @OnMessage 

        public void onMessage(String message) throws IOException { 

       

<p><code>            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>            

        

       

        @OnError 

        public void onError(Session session, Throwable error) { 

<p><code>            error.printStackTrace(); 

        

       

        public void sendMessageTo(String message, String To) throws IOException { 

<p><code>            // 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>            

        

           

        public void sendMessageAll(String message) throws IOException { 

<p><code>            for (WebSocket item : clients.values()) { 

<p><code>                item.session.getAsyncRemote().sendText(message); 

<p><code>            

        

       

        public static synchronized int getOnlineCount() { 

<p><code>            return onlineCount; 

        

       

        public static synchronized void addOnlineCount() { 

<p><code>            WebSocket.onlineCount ; 

        

       

        public static synchronized void subOnlineCount() { 

<p><code>            WebSocket.onlineCount--; 

        

       

        public static synchronized Map<String, WebSocket> getClients() { 

<p><code>            return clients; 

        

}

  2.在自己代码中的调用:

1

2

3

4

5

WebSocket ws = new WebSocket();

JSONObject jo = new JSONObject();

jo.put("message""这是后台返回的消息!");

jo.put("To",invIO.getIoEmployeeUid());

ws.onMessage(jo.toString());

  7.所需maven依赖:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!-- webSocket 开始-->

<dependency>

    <groupId>javax.websocket</groupId>

    <artifactId>javax.websocket-api</artifactId>

    <version>1.1</version>

    <scope>provided</scope>

</dependency>

 

<dependency>

    <groupId>javax</groupId>

    <artifactId>javaee-api</artifactId>

    <version>7.0</version>

    <scope>provided</scope>

</dependency>

<!-- webSocket 结束-->

相关文章:

Java中websocket消息推送

一个基于WebSocket的WEB消息推送框架

相关视频:

Websocket视频教程

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

See all articles