>  기사  >  Java  >  Java 백그라운드 메시지 푸시 구현을 위한 WebSocket의 원리와 기본 지식

Java 백그라운드 메시지 푸시 구현을 위한 WebSocket의 원리와 기본 지식

php是最好的语言
php是最好的语言원래의
2018-08-03 11:35:183027검색

1. WebSocket이란 무엇입니까? 브라우저와 서버 간의 전이중 통신을 구현하여 서버가 클라이언트에 정보를 사전에 보낼 수 있도록 합니다.

2. 구현 원칙

웹소켓 연결을 구현하는 과정에서 브라우저를 통해 웹소켓 연결 요청을 보내고 서버가 응답을 보내는 과정입니다. 일반적으로 "악수"라고합니다. WebSocket API에서는 브라우저와 서버가 핸드셰이크 작업만 수행하면 브라우저와 서버 사이에 빠른 채널이 형성됩니다. 데이터는 둘 사이에서 직접 전송될 수 있습니다.

3. 장점

이전 메시지 푸시 메커니즘에서는 특정 시간 간격으로 브라우저에 의해 자동으로 요청을 발행하는 Ajax 폴링이 사용되었습니다. 서버에서 메시지를 적극적으로 가져오는 것은 본질적으로 HTTP 요청이고 매우 서툴기 때문에 리소스를 많이 소모합니다. WebSocket은 브라우저와 서버 간의 핸드셰이크를 완료하고 나면 서버는 클라이언트에 적극적으로 데이터를 전송할 수 있으며 클라이언트는 언제든지 서버에 데이터를 보낼 수도 있습니다.

4.WebSocket과 소켓의 차이점

1.WebSocket:

#🎜 🎜 #
  1. 웹소켓 통신의 확립 단계는 http 프로토콜에 의존합니다. 초기 핸드셰이크 단계는 http 프로토콜입니다. 핸드셰이크가 완료된 후 웹소켓 프로토콜로 전환되며 http 프로토콜과 완전히 분리됩니다.
    1. 통신을 설정할 때 클라이언트는 적극적으로 연결 요청을 시작하고 서버는 수동적으로 수신합니다.

    2. 통신 연결이 설정되면 통신은 "전이중" 모드가 됩니다. 즉, 서버와 클라이언트 모두 언제든지 자유롭게 데이터를 보낼 수 있으며, 이는 서버가 실시간 데이터를 적극적으로 푸시하려는 비즈니스 시나리오에 매우 적합합니다.

    3. 상호작용 모드는 더 이상 "요청-응답" 모드가 아니며 통신 프로토콜은 완전히 개발자가 설계했습니다.
    4. 통신 데이터는 "프레임"을 기반으로 하며 텍스트 데이터 또는 바이너리 데이터를 직접 전송할 수 있어 효율성이 높습니다. 물론 개발자는 포장, 포장 풀기, 번호 매기기 등의 기술적인 세부 사항도 고려해야 합니다.
    5. 2.소켓:

    6. 서버는 통신을 모니터링하고 클라이언트에 수동적으로 서비스를 제공합니다. 클라이언트는 통신을 설정하기 위해 서버에 대한 연결 요청을 적극적으로 시작합니다.
    7. 모든 상호 작용은 클라이언트가 적극적으로 요청(요청)을 시작하고 서버가 수동적으로 응답(응답)하는 것입니다.

    8. 서버가 적극적으로 클라이언트에 데이터를 푸시할 수 없습니다.

    9. 전달되는 데이터는 텍스트 형식을 기반으로 합니다. 바이너리 데이터(예: 사진 등)는 전송하기 전에 base64 및 기타 수단을 사용하여 텍스트로 변환되어야 합니다.

    10. 5. WebSocket 클라이언트:

    11. # 🎜🎜#

1

23var username = "${loginUsername}" // 현재 로그인한 사용자의 사용자 이름을 가져옵니다. <td> <p><code> // 경고(사용자 이름)var websocket = null;

var host = document.location.host; 

var username = "${loginUsername}"// 获得当前登录人员的userName 

 // alert(username)

//判断当前浏览器是否支持WebSocket 

if ('WebSocket' in window) { 

    alert("浏览器支持Websocket")

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

else 

    alert('当前浏览器 Not support websocket'

//현재 브라우저가 WebSocket을 지원하는지 확인

if('WebSocket'in window) { #🎜🎜# #🎜🎜# alert("브라우저가 Websocket을 지원합니다.")#🎜🎜# #🎜🎜# websocket = newWebSocket('ws://'+호스트+'/mm-dorado/webSocket/'+사용자 이름) #🎜🎜# #🎜🎜#} else{ #🎜🎜# #🎜🎜# alert('현재 브라우저는 웹소켓을 지원하지 않습니다.') #🎜🎜# #🎜🎜#} #🎜🎜# #🎜🎜# #🎜🎜#

//연결 오류 발생 시 콜백 방법//连接发生错误的回调方法 

websocket.onerror = function() { 

  alert("WebSocket连接发生错误")

   setMessageInnerHTML("WebSocket连接发生错误"); 

};  

   

//连接成功建立的回调方法 

websocket.onopen = function() {

  alert("WebSocket连接成功"

   setMessageInnerHTML("WebSocket连接成功"); 

   

//接收到消息的回调方法 

websocket.onmessage = function(event) {

    alert("接收到消息的回调方法"

    alert("这是后台推送的消息:"+event.data);

     websocket.close();

    alert("webSocket已关闭!")

   

//连接关闭的回调方法 

websocket.onclose = function() { 

    setMessageInnerHTML("WebSocket连接关闭"); 

   

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 

window.onbeforeunload = function() { 

    closeWebSocket(); 

   

//关闭WebSocket连接 

function closeWebSocket() { 

    websocket.close(); 

 

//将消息显示在网页上

    function setMessageInnerHTML(innerHTML) {

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

    }

websocket.onerror = function() {  alert("WebSocket 연결 오류")

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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 호스트 = document.location.host

setMessageInnerHTML("WebSocket 연결 오류") 🎜 🎜} 🎜 🎜 🎜 🎜//연결 성공 시 콜백 방법 🎜 🎜websocket.onopen = function() {🎜 🎜 alert("WebSocket 연결 성공") 🎜 🎜 setMessageInnerHTML("WebSocket 연결 성공") 🎜 🎜} 🎜 🎜 🎜 🎜//메시지 수신 콜백 방법 🎜 🎜websocket.onmessage = 함수(이벤트) {🎜 🎜 alert("메시지 수신을 위한 콜백 방법") 🎜 🎜 alert("백그라운드에서 푸시된 메시지입니다:"+event.data);🎜 🎜  websocket.close();🎜 🎜 alert("webSocket이 닫혔습니다!")🎜 🎜} 🎜 🎜 🎜 🎜//연결 종료를 위한 콜백 방법 🎜 🎜websocket.onclose = function() { 🎜 🎜 setMessageInnerHTML("WebSocket 연결이 닫혔습니다.") 🎜 🎜} 🎜 🎜 🎜 🎜//창 닫기 이벤트를 수신합니다. 창이 닫힐 때 연결이 끊어지기 전에 창이 닫히지 않도록 웹소켓 연결을 적극적으로 닫아 서버에서 예외를 발생시킵니다. 🎜 🎜window.onbeforeunload = function() { 🎜 🎜 closeWebSocket() 🎜; 🎜} 🎜 🎜 🎜 🎜//WebSocket 연결 닫기 🎜 🎜함수 closeWebSocket() { 🎜 🎜 websocket.close() 🎜 🎜} 🎜 🎜 🎜 🎜//웹페이지에 메시지 표시🎜 🎜 함수 setMessageInnerHTML(innerHTML) {🎜 🎜 document.getElementById('메시지').innerHTML += innerHTML + '<br />';🎜 🎜 }🎜 🎜 🎜🎜🎜

6. WebSocket 서버(자바 배경):

1. 핵심 클래스:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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

패키지 com.mes.util;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; 

           

        @OnOpen 

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

       

            this.username = username; 

            this.session = session; 

               

            addOnlineCount(); 

#🎜🎜# #🎜🎜#가져오기 java.io.IOException;#🎜🎜# #🎜🎜#가져오기 java.util.Map;#🎜🎜# #🎜🎜#가져오기 java.util.concurrent.ConcurrentHashMap;#🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜#가져오기 javax.websocket.OnClose;#🎜🎜# #🎜🎜#가져오기 javax.websocket.OnError;#🎜🎜# #🎜🎜#가져오기 javax.websocket.OnMessage;#🎜🎜# #🎜🎜#가져오기 javax.websocket.OnOpen;#🎜🎜# #🎜🎜#가져오기 javax.websocket.Session;#🎜🎜# #🎜🎜#가져오기 javax.websocket.server.PathParam;#🎜🎜# #🎜🎜#가져오기 javax.websocket.server.ServerEndpoint;#🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜#가져오기 org.springframework.stereotype.Component;#🎜🎜# #🎜🎜#가져오기 org.springframework.stereotype.Service;#🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜#가져오기 com.google.gson.JsonObject;#🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜#가져오기 net.sf.json.JSONObject;#🎜🎜# #🎜🎜#@ServerEndpoint("/webSocket/{username}") #🎜🎜# #🎜🎜# 공개 클래스 WebSocket { #🎜🎜# #🎜🎜# private static int onlineCount = 0 코드 코드> #🎜🎜# #🎜🎜# private static Map<String, WebSocket> 클라이언트 = new ConcurrentHashMap<String, WebSocket>() #🎜🎜# #🎜🎜# 비공개 세션 세션 #🎜🎜# #🎜🎜# 비공개 문자열 사용자 이름 #🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜# @OnOpen #🎜🎜# #🎜🎜# 공개 void onOpen(@PathParam(<code>"사용자 이름") 문자열 사용자 이름, 세션 세션) throw IOException { #🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜# this.username = 사용자 이름 #🎜🎜# #🎜🎜# this.session = 세션 #🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜# addOnlineCount() #🎜🎜#

            clients.put(사용자 이름, this);            clients.put(username, this);

            System.out.println("已连接");

        

       

        @OnClose 

        public void onClose() throws IOException { 

            clients.remove(username); 

            subOnlineCount(); 

        

       

        @OnMessage 

        public void onMessage(String message) throws IOException { 

       

            JSONObject jsonTo = JSONObject.fromObject(message); 

            String mes = (String) jsonTo.get("message");

             

            if (!jsonTo.get("To").equals("All")){ 

                sendMessageTo(mes, jsonTo.get("To").toString()); 

            }else

                sendMessageAll("给所有人"); 

            

        

       

        @OnError 

        public void onError(Session session, Throwable error) { 

            error.printStackTrace(); 

        

       

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

            // session.getBasicRemote().sendText(message); 

            //session.getAsyncRemote().sendText(message); 

            for (WebSocket item : clients.values()) { 

                if (item.username.equals(To) ) 

                    item.session.getAsyncRemote().sendText(message); 

            System.out.println("已连接");#🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        @OnClose #🎜🎜# #🎜🎜#        public void onClose() throws IOException { #🎜🎜# #🎜🎜#            clients.remove(사용자 이름); #🎜🎜# #🎜🎜#            subOnlineCount(); #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        @OnMessage #🎜🎜# #🎜🎜#        public void onMessage(String message) throws  IO예외 { #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#            JSONObject jsonTo = JSONObject.fromObject(message); #🎜🎜# #🎜🎜#            String mes = (String) jsonTo.get("message");#🎜🎜 # #🎜🎜#             #🎜🎜# #🎜🎜#            if (!jsonTo.get("To").equals(<code>"모두")){ #🎜🎜# #🎜🎜#               sendMessageTo(mes, jsonTo.get("To").toString()); #🎜🎜# #🎜🎜#            }else#🎜🎜# #🎜🎜#                sendMessageAll("给所有人"); #🎜🎜# #🎜🎜#            } #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        @OnError #🎜🎜# #🎜🎜#        public void onError(세션 세션, Throwable 오류) { #🎜🎜# #🎜🎜#            error.printStackTrace(); #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        public void sendMessageTo(String message, String To) throws IO예외 { #🎜🎜# #🎜🎜#            // session.getBasicRemote().sendText(message); #🎜🎜# #🎜🎜#            //session.getAsyncRemote().sendText(message); #🎜🎜# #🎜🎜#            for (WebSocket 항목 : 클라이언트.값()) { #🎜🎜# #🎜🎜#               if (item.username.equals(To) ) #🎜🎜# #🎜🎜#                   item.session.getAsyncRemote().sendText(message); #🎜🎜#

            }             

        

           

        public void sendMessageAll(String message) throws IOException { 

            for (WebSocket item : clients.values()) { 

                item.session.getAsyncRemote().sendText(message); 

            

        

       

        public static synchronized int getOnlineCount() { 

            return onlineCount; 

        

       

        public static synchronized void addOnlineCount() { 

            WebSocket.onlineCount++; 

        

       

        public static synchronized void subOnlineCount() { 

            WebSocket.onlineCount--; 

        

       

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

            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());

        
        public void sendMessageAll(String message) throws  IO예외 { #🎜🎜# #🎜🎜#            for (WebSocket 항목 : 클라이언트.값()) { #🎜🎜# #🎜🎜#                item.session.getAsyncRemote().sendText(message); #🎜🎜# #🎜🎜#            } #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        공개 정적 동기화 int getOnlineCount() { #🎜🎜# #🎜🎜#            return onlineCount; #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        공개 정적 동기화 void addOnlineCount() { #🎜🎜# #🎜🎜#            WebSocket.onlineCount++; #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        공개 정적 동기화 void subOnlineCount() { #🎜🎜# #🎜🎜#            WebSocket.onlineCount--; #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#       #🎜🎜# #🎜🎜#        공개 정적 동기화 Map<String, WebSocket> getClients() { #🎜🎜# #🎜🎜#            반품 고객; #🎜🎜# #🎜🎜#        #🎜🎜# #🎜🎜#}#🎜🎜# #🎜🎜# #ㅋㅋㅋ > #🎜🎜#1#🎜🎜# #🎜🎜#2#🎜🎜# #🎜🎜#3#🎜🎜# #🎜🎜#4#🎜🎜# #🎜🎜#5#🎜🎜# #🎜🎜# #🎜🎜#WebSocket ws = new WebSocket();#🎜🎜# #🎜🎜#JSONObject jo = new JSONObject();#🎜🎜# #🎜🎜#jo.put("메시지""这是后台返回的消息!");#🎜🎜# #🎜🎜#jo.put("받는 사람",invIO.getIoEmployeeUid());#🎜🎜# #🎜🎜#ws.onMessage(jo.toString());#🎜🎜# #🎜🎜# #🎜🎜##🎜🎜##🎜🎜#

  7.所需maven依赖:

    <groupId>javax.websocket</groupId>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!-- webSocket 开始--><!-- 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 结束-->

<의존성>
    <artifactId>javax.websocket-api</artifactId>

    <version>1.1</version>     <scope>제공</scope>

</의존성>  

<의존성>

    <groupId>javax</groupId>

    <artifactId>javaee-api</artifactId>

    <version>7.0</version>🎜 🎜    <scope>제공</scope>🎜 🎜</의존성>🎜 🎜<!-- webSocket 结束-->🎜 🎜 🎜🎜🎜상关文章:🎜🎜🎜Java中websocket消息推送🎜🎜🎜🎜一个基于WebSocket의WEB消息推送框架🎜🎜🎜상关视频:🎜🎜🎜🎜Websocket视频教程🎜🎜

위 내용은 Java 백그라운드 메시지 푸시 구현을 위한 WebSocket의 원리와 기본 지식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.