websocket实现简单聊天室

7 篇文章 0 订阅
2 篇文章 0 订阅
1. websocket

这篇博主写的比较清楚:
https://www.cnblogs.com/jingmoxukong/p/7755643.html

1. 客户端实现

(1)先画一个简单页面

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
<div>
姓名: <input id="name"/> 联系人: <input id="anther"/> 
<button onclick="initWebSocket()">登录</button> 
<br/>

输入: <input id="ipt" /> 
<button onclick="send()">发送</button> 
<br/>

<div id="chatList"></div>
</div>
</body>
</html>

页面长这样:
在这里插入图片描述

(2) 编写js

//初始化一个 WebSocket 对象
var g_ws;

function $(id) {
  return document.getElementById(id);
}

function initWebSocket() {
  var name = $("name").value;
  g_ws = new WebSocket("ws://localhost:7545/websocket/websocket/" + name);
  
  // 建立 web socket 连接成功触发事件
  g_ws.onopen = function () {};
  
  // 接收服务端数据时触发事件
  g_ws.onmessage = function (evt) {
    var received_msg = JSON.parse(evt.data);
    $("chatList").innerHTML += '<div>' + received_msg.msg + '</div>';
  };
}

function send() {
  var msg = $("ipt").value;
  var name = $("anther").value;
  g_ws.send(JSON.stringify({
    to: name,
    msg: msg
  }));
}
2. 服务端实现

(1) 依赖包
核心依赖:javax.websocket-api

<dependency>
  <groupId>javax.websocket</groupId>
  <artifactId>javax.websocket-api</artifactId>  
  <version>1.0</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.47</version>
</dependency>

(2) java实现代码

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;

@ServerEndpoint("/websocket/{username}")
public class WebSocket {

  private static int onlineCount = 0;
  private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
  private Session session;
  private String username;

  @OnOpen
  public void onOpen(@PathParam("username") String username, Session session) throws IOException {

    this.username = username;
    this.session = session;

    addOnlineCount();
    clients.put(username, this);
  }

  @OnClose
  public void onClose() throws IOException {
    clients.remove(username);
    subOnlineCount();
  }

  @OnMessage
  public void onMessage(String message) throws IOException {
    JSONObject jsonTo = JSONObject.parseObject(message);
    if (!jsonTo.get("to").equals("All")) {
      sendMessageTo(message, jsonTo.get("to").toString());
    } else {
      sendMessageAll(message);
    }
  }

  @OnError
  public void onError(Session session, Throwable error) {
    error.printStackTrace();
  }

  public void sendMessageTo(String message, String To) throws IOException {
    for (WebSocket item : clients.values()) {
      if (item.username.equals(To))
        item.session.getAsyncRemote().sendText(message);
    }
  }

  public void sendMessageAll(String message) throws IOException {
    for (WebSocket item : clients.values()) {
      item.session.getAsyncRemote().sendText(message);
    }
  }

  public static synchronized int getOnlineCount() {
    return onlineCount;
  }

  public static synchronized void addOnlineCount() {
    WebSocket.onlineCount++;
  }

  public static synchronized void subOnlineCount() {
    WebSocket.onlineCount--;
  }

  public static synchronized Map<String, WebSocket> getClients() {
    return clients;
  }
}
3. 效果

下面是基础效果:
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三和小钢炮

谢谢客官~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值