栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

WebSocket实现Web聊天室功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WebSocket实现Web聊天室功能

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

一.客户端

JS代码如下:


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

二.服务器

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 webSocketSet = new HashSet<>();    //静态变量,用来存放在线用户
  private 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());
  }

  
  @onMessage
  public void onMessage(String data, Session session) {
    Mess mess = new Gson().fromJson(data, Mess.class);
    System.out.printf("来%s的消息:%sn", mess.getUsername(), mess.getContent());
    //群发消息
    for(ChatService item: webSocketSet){
      try {
 item.sendMessage(mess);
      } catch (IOException e) {
 e.printStackTrace();
 continue;
      }
    }
  }
  
  
  @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--;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140086.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号