国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

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

服務(wù)器之家 - 編程語言 - Java教程 - java WebSocket實現(xiàn)聊天消息推送功能

java WebSocket實現(xiàn)聊天消息推送功能

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

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

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

環(huán)境:

jdk.1.7.0_51

apache-tomcat-7.0.53

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

chatannotation消息發(fā)送類:

?
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 消息推送服務(wù)類
 * @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);
  }
 
 
  /**
   * 消息發(fā)送觸發(fā)方法
   * @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);
  }
 
  /**
   * 消息發(fā)送方法
   * @param msg
   */
  private static void broadcast(string msg) {
   if(msg.indexof("guest0")!=-1){
   senduser(msg);
   } else{
   sendall(msg);
   }
  }
  
  /**
   * 向所有用戶發(fā)送
   * @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);
      }
    }
  }
  
  /**
   * 向指定用戶發(fā)送消息
   * @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="請輸入內(nèi)容" id="chat" />
  </p>
  <div id="console-container">
    <div id="console"/>
  </div>
</div>
</body>
</html>

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

程序截圖,guest0用戶發(fā)送信息的信息,在后臺進(jìn)行了判斷只發(fā)送給自己:

java WebSocket實現(xiàn)聊天消息推送功能

guest1:

java WebSocket實現(xiàn)聊天消息推送功能

guest2:

java WebSocket實現(xiàn)聊天消息推送功能

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

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

延伸 · 閱讀

精彩推薦
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25 Weibo Article 26 Weibo Article 27 Weibo Article 28 Weibo Article 29 Weibo Article 30 Weibo Article 31 Weibo Article 32 Weibo Article 33 Weibo Article 34 Weibo Article 35 Weibo Article 36 Weibo Article 37 Weibo Article 38 Weibo Article 39 Weibo Article 40
主站蜘蛛池模板: 蜜桃成人在线 | 求av网站 | 亚洲成人av一区二区三区 | 91色视频在线观看 | 欧美成人免费在线视频 | 国产精品久久久久久久久久久久久久 | 黄色一级视频 | 日本在线免费观看视频 | 久久中文字幕一区 | h片在线 | 久久丁香 | 亚洲欧美精品 | 亚洲欧美在线一区 | 免费一区二区三区 | 午夜视频在线观看网站 | 中国a一片一级一片 | 激情综合激情 | 国产深夜视频在线观看 | 久久久久久久国产精品视频 | 国产模特私拍xxxx | 欧美日韩亚洲成人 | 久久成人精品视频 | 最近日韩中文字幕 | 欧美视频免费 | 免费视频一区二区 | 国产精品久久久久久久久久久久 | 网友自拍第一页 | 91亚洲国产成人久久精品网站 | 午夜午夜精品一区二区三区文 | 在线看黄网站 | 成人免费视频网站在线观看 | 亚洲欧美激情精品一区二区 | 精品无码久久久久久国产 | 成人在线免费视频 | 91av免费在线观看 | 国产精品爱久久久久久久 | 精品国产一级 | 激情五月综合 | 免费裸体视频网站 | 国产一区二区三区欧美 | 亚洲三级在线免费观看 |