一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - java WebSocket實現聊天消息推送功能

java WebSocket實現聊天消息推送功能

2021-05-13 12:02小爺胡漢三 Java教程

這篇文章主要為大家詳細介紹了java WebSocket實現聊天消息推送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了java websocket實現聊天消息推送功能的具體代碼,供大家參考,具體內容如下

環境:

jdk.1.7.0_51

apache-tomcat-7.0.53

java jar包:tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar

chatannotation消息發送類:

?
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import java.io.ioexception;
import java.util.hashmap;
import java.util.map;
import java.util.concurrent.atomic.atomicinteger;
 
import javax.websocket.onclose;
import javax.websocket.onerror;
import javax.websocket.onmessage;
import javax.websocket.onopen;
import javax.websocket.session;
import javax.websocket.server.serverendpoint;
 
import org.apache.juli.logging.log;
import org.apache.juli.logging.logfactory;
 
import com.util.htmlfilter;
 
/**
 * websocket 消息推送服務類
 * @author 胡漢三
 *
 * 2014-11-18 下午7:53:13
 */
@serverendpoint(value = "/websocket/chat")
public class chatannotation {
 
  private static final log log = logfactory.getlog(chatannotation.class);
 
  private static final string guest_prefix = "guest";
  private static final atomicinteger connectionids = new atomicinteger(0);
  private static final map<string,object> connections = new hashmap<string,object>();
 
  private final string nickname;
  private session session;
 
  public chatannotation() {
    nickname = guest_prefix + connectionids.getandincrement();
  }
 
 
  @onopen
  public void start(session session) {
    this.session = session;
    connections.put(nickname, this);
    string message = string.format("* %s %s", nickname, "has joined.");
    broadcast(message);
  }
 
 
  @onclose
  public void end() {
    connections.remove(this);
    string message = string.format("* %s %s",
        nickname, "has disconnected.");
    broadcast(message);
  }
 
 
  /**
   * 消息發送觸發方法
   * @param message
   */
  @onmessage
  public void incoming(string message) {
    // never trust the client
    string filteredmessage = string.format("%s: %s",
        nickname, htmlfilter.filter(message.tostring()));
    broadcast(filteredmessage);
  }
 
  @onerror
  public void onerror(throwable t) throws throwable {
    log.error("chat error: " + t.tostring(), t);
  }
 
  /**
   * 消息發送方法
   * @param msg
   */
  private static void broadcast(string msg) {
   if(msg.indexof("guest0")!=-1){
   senduser(msg);
   } else{
   sendall(msg);
   }
  }
  
  /**
   * 向所有用戶發送
   * @param msg
   */
  public static void sendall(string msg){
   for (string key : connections.keyset()) {
     chatannotation client = null ;
      try {
       client = (chatannotation) connections.get(key);
        synchronized (client) {
          client.session.getbasicremote().sendtext(msg);
        }
      } catch (ioexception e) {
        log.debug("chat error: failed to send message to client", e);
        connections.remove(client);
        try {
          client.session.close();
        } catch (ioexception e1) {
          // ignore
        }
        string message = string.format("* %s %s",
            client.nickname, "has been disconnected.");
        broadcast(message);
      }
    }
  }
  
  /**
   * 向指定用戶發送消息
   * @param msg
   */
  public static void senduser(string msg){
   chatannotation c = (chatannotation)connections.get("guest0");
 try {
  c.session.getbasicremote().sendtext(msg);
 } catch (ioexception e) {
  log.debug("chat error: failed to send message to client", e);
      connections.remove(c);
      try {
        c.session.close();
      } catch (ioexception e1) {
        // ignore
      }
      string message = string.format("* %s %s",
          c.nickname, "has been disconnected.");
      broadcast(message);
 }
  }
}

htmlfilter工具類:

?
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
/**
 * html 工具類
 *
 * @author 胡漢三
 */
public final class htmlfilter {
  public static string filter(string message) {
    if (message == null)
      return (null);
    char content[] = new char[message.length()];
    message.getchars(0, message.length(), content, 0);
    stringbuilder result = new stringbuilder(content.length + 50);
    for (int i = 0; i < content.length; i++) {
      switch (content[i]) {
      case '<':
        result.append("<");
        break;
      case '>':
        result.append(">");
        break;
      case '&':
        result.append("&");
        break;
      case '"':
        result.append(""");
        break;
      default:
        result.append(content[i]);
      }
    }
    return (result.tostring());
  }
}

頁面:

?
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
 
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>測試</title>
  <style type="text/css">
    input#chat {
      width: 410px
    }
 
    #console-container {
      width: 400px;
    }
 
    #console {
      border: 1px solid #cccccc;
      border-right-color: #999999;
      border-bottom-color: #999999;
      height: 170px;
      overflow-y: scroll;
      padding: 5px;
      width: 100%;
    }
 
    #console p {
      padding: 0;
      margin: 0;
    }
 </style>
  <script type="text/javascript">
 
    var chat = {};
 
    chat.socket = null;
 
    chat.connect = (function(host) {
      if ('websocket' in window) {
        chat.socket = new websocket(host);
      } else if ('mozwebsocket' in window) {
        chat.socket = new mozwebsocket(host);
      } else {
        console.log('error: websocket is not supported by this browser.');
        return;
      }
 
      chat.socket.onopen = function () {
        console.log('info: websocket connection opened.');
        document.getelementbyid('chat').onkeydown = function(event) {
          if (event.keycode == 13) {
            chat.sendmessage();
          }
        };
      };
 
      chat.socket.onclose = function () {
        document.getelementbyid('chat').onkeydown = null;
        console.log('info: websocket closed.');
      };
 
      chat.socket.onmessage = function (message) {
        console.log(message.data);
      };
    });
 
    chat.initialize = function() {
      if (window.location.protocol == 'http:') {
        chat.connect('ws://' + window.location.host + '/socket2/websocket/chat');
      } else {
        chat.connect('wss://' + window.location.host + '/socket2/websocket/chat');
      }
    };
 
    chat.sendmessage = (function() {
      var message = document.getelementbyid('chat').value;
      if (message != '') {
        chat.socket.send(message);
        document.getelementbyid('chat').value = '';
      }
    });
 
    var console = {};
 
    console.log = (function(message) {
      var console = document.getelementbyid('console');
      var p = document.createelement('p');
      p.style.wordwrap = 'break-word';
      p.innerhtml = message;
      console.appendchild(p);
      while (console.childnodes.length > 25) {
        console.removechild(console.firstchild);
      }
      console.scrolltop = console.scrollheight;
    });
 
    chat.initialize();
 
 
    document.addeventlistener("domcontentloaded", function() {
      // remove elements with "noscript" class - <noscript> is not allowed in xhtml
      var noscripts = document.getelementsbyclassname("noscript");
      for (var i = 0; i < noscripts.length; i++) {
        noscripts[i].parentnode.removechild(noscripts[i]);
      }
    }, false);
 
  </script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">seems your browser doesn't support javascript! websockets rely on javascript being enabled. please enable
  javascript and reload this page!</h2></div>
<div>
  <p>
    <input type="text" placeholder="請輸入內容" id="chat" />
  </p>
  <div id="console-container">
    <div id="console"/>
  </div>
</div>
</body>
</html>

可指定發送給某個用戶,也可全部發送,詳情見chatannotation類的broadcast方法。
程序發布時記得刪除tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar這三個jar包在啟動tomcat。

程序截圖,guest0用戶發送信息的信息,在后臺進行了判斷只發送給自己:

java WebSocket實現聊天消息推送功能

guest1:

java WebSocket實現聊天消息推送功能

guest2:

java WebSocket實現聊天消息推送功能

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/hzw2312/article/details/41252159/

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美色图亚洲天堂 | 忘忧草秋观看未满十八 | 国产精品女主播大秀在线 | 日本嫩模| 热久久99精品这里有精品 | 国产探花视频在线观看 | 亚洲伦理影院 | 九九99亚洲精品久久久久 | 免费精品视频在线 | zol中关村在线官网 yy6080欧美三级理论 | 亚洲国产欧美在线看片 | 日本护士撒尿xxxx欧美 | 青青青久在线视频免费观看 | 日本红色高清免费观看 | 亚洲激情视频在线 | 韩国情事伦理片观看地址 | 色综合天天综合 | 99re7在线精品免费视频 | 日韩人成免费网站大片 | 亚洲天堂影院在线观看 | 国产一区二区三区免费在线视频 | 2020国产精品亚洲综合网 | 亚洲一卡2卡4卡5卡6卡残暴在线 | 免费超级乱淫播放手机版 | 天堂伊人网| 99精品免费视频 | 国产福利视频一区二区微拍视频 | 国产婷婷高清在线观看免费 | 拔插拔插8x8x海外华人免费视频 | 精品一区二区三区五区六区 | 日韩欧美国产一区二区三区 | 强行扒开美女大腿挺进 | 欧美亚洲国产精品久久久 | 俄罗斯bbbbbbbbb大片 | 精品一区二区三区免费视频 | 国产精品久久久久久久久免费hd | 日本福利片国产午夜久久 | 91桃花 | 免费又爽又黄禁片视频在线播放 | 成人观看免费大片在线观看 | 色女阁|