服务器之家:专注于服务器技术及软件下载分享
分类导航

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/

延伸 · 阅读

精彩推荐