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

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - WebSocket实现Web聊天室功能

WebSocket实现Web聊天室功能

2021-05-29 11:45DOLFAMINGO Java教程

这篇文章主要为大家详细介绍了WebSocket实现Web聊天室功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文为大家分享了websocket实现web聊天室的具体代码,供大家参考,具体内容如下

一.客户端

WebSocket实现Web聊天室功能

js代码如下:

?
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
/*
 *   这部分js将websocket封装起来
 */
  var websocket = null;
  //判断当前浏览器是否支持websocket
  if ('websocket' in window) {
    websocket = new websocket("ws://localhost:8080/goodman/chatservice");
  }
  else {
    alert('当前浏览器 not support websocket')
  }
  
   //连接成功建立的回调方法
  websocket.onopen = function () {
    alert("websocket连接成功");
  }
 
  //连接发生错误的回调方法
  websocket.onerror = function () {
    alert("websocket连接发生错误");
  };
  
   //发送消息
  function sendmess(content) {
     var json ="{'username':'"+'${sessionscope.username }'+"', 'content':'"+content+"'}";
    websocket.send(json);
  }
 
  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    var jsonstring = event.data;    //接收到的信息存放在event.data中
    var data = json.parse(jsonstring);  //将json字符串转换成js对象
    // 然后输出data
  }
 
   //连接关闭的回调方法
  websocket.onclose = function () {
    alert("websocket连接关闭");
  }
 
  //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  window.onbeforeunload = function () {
    closewebsocket();
  }
 
  //关闭websocket连接
  function closewebsocket() {
    websocket.close();
  }

二.服务器

?
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
import java.io.ioexception;
import java.util.date;
import java.util.hashset;
import java.util.set;
import javax.websocket.*;
import javax.websocket.server.serverendpoint;
import com.google.gson.gson;
 
class mess{    //封装一条消息
  private string username;
  private string content;
  private string date;
  public mess(string username, string content, string date) {
    super();
    this.username = username;
    this.content = content;
    this.date = date;
  }
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getcontent() {
    return content;
  }
  public void setcontent(string content) {
    this.content = content;
  }
  public string getdate() {
    return date;
  }
  public void setdate(string date) {
    this.date = date;
  }
}
 
@serverendpoint("/chatservice")
public class chatservice {      //每进入一个用户,就新建一个chatservice对象
  
  private static int onlinecount = 0; //静态变量, 用来记录当前在线连接数
  private static set<chatservice> websocketset = new hashset<>();    //静态变量,用来存放在线用户
  private session session;   //用于存储与该用户的会话,要通过它来给客户端发送数据
 
  /**
   * 连接建立成功调用的方法
   * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
   */
  @onopen
  public void onopen(session session){
    this.session = session;
    websocketset.add(this);   //加入set中
    addonlinecount();      //在线数加1
    system.out.println("有新连接加入!当前在线人数为" + getonlinecount());
  }
  
  /**
   * 连接关闭调用的方法
   */
  @onclose
  public void onclose(){
    websocketset.remove(this); //从set中删除
    subonlinecount();      //在线数减1
    system.out.println("有一连接关闭!当前在线人数为" + getonlinecount());
  }
 
  /**
   * 收到客户端消息后调用的方法
   * @param message 客户端发送过来的消息
   * @param session 可选的参数
   */
  @onmessage
  public void onmessage(string data, session session) {
    mess mess = new gson().fromjson(data, mess.class);
    system.out.printf("来%s的消息:%s\n", mess.getusername(), mess.getcontent());
    //群发消息
    for(chatservice item: websocketset){
      try {
        item.sendmessage(mess);
      } catch (ioexception e) {
        e.printstacktrace();
        continue;
      }
    }
  }
  
  /**
   * 发生错误时调用
   * @param session
   * @param error
   */
  @onerror
  public void onerror(session session, throwable error){
    system.out.println("发生错误");
    error.printstacktrace();
  }
 
  //以下为辅助函数
  public void sendmessage(mess mess) throws ioexception{
 
    string datatime = new java.text.simpledateformat("yyyy-mm-dd hh:mm:ss").format(new date());
    mess.setdate(datatime);
    string jsoninfo = new gson().tojson(mess);    //将消息对象转换成json字符串
    this.session.getasyncremote().sendtext(jsoninfo); //通过session异步地将信息发送到客户端上
  }
 
  public static synchronized int getonlinecount() {
    return onlinecount;
  }
 
  public static synchronized void addonlinecount() {
    chatservice.onlinecount++;
  }
 
  public static synchronized void subonlinecount() {
    chatservice.onlinecount--;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/DOLFAMINGO/p/9544955.html

延伸 · 阅读

精彩推荐