用java WebSocket做一个聊天室
作者:小二少爷 时间:2021-11-30 00:39:55
最近一个项目中,需要用到Java的websocket新特性,于是就学了一下,感觉这技术还挺好玩的,瞬间知道网页上面的那些在线客服是怎么做的了。
先看图:
实现了多客户机进行实时通讯。
下面看代码项目结构图:很简单,就1个类,1个页面
然后看具体代码
先看后端代码
package com.main;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/websocket")
public class H5ServletServerSocket {
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<H5ServletServerSocket> webSocketSet = new CopyOnWriteArraySet<H5ServletServerSocket>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
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 message, Session session) {
System.out.println("来自客户端的消息:" + message);
// 群发消息
for (H5ServletServerSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
// this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
H5ServletServerSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
H5ServletServerSocket.onlineCount--;
}
}
接下来是前端页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML>
<html>
<head>
<base href="<%=basePath%>">
<title>My WebSocket</title>
</head>
<body>
欢迎进入聊天室
<div id="message" style="color: blue">【状态】</div>
<br /> 昵称
<input id="username" type="text" required="required"/>
<br> 内容
<input id="text" type="text" />
<br />
<button onclick="send()">发送</button>
<button onclick="closeWebSocket()">关闭</button>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://10.1.1.106:8080/Socket/websocket");
} else {
alert('不支持WebSocket!')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event) {
setMessageInnerHTML("聊天室开启");
}
//接收到消息的回调方法
websocket.onmessage = function() {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("聊天室关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var username = document.getElementById('username').value;
var message = document.getElementById('text').value;
var msg = "【" + username + "】发言:" + message
websocket.send(msg);
}
</script>
</html>
标签:java,WebSocket,聊天室
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring main方法中如何调用Dao层和Service层的方法
2023-11-28 23:15:19
![](https://img.aspxhome.com/file/2023/3/60753_0s.png)
MybatisPlus多表连接查询的问题及解决方案
2023-11-25 22:09:06
![](https://img.aspxhome.com/file/2023/8/60348_0s.png)
Java如何实现自定义异常类
2023-06-21 23:44:01
android6.0权限动态申请框架permissiondispatcher的方法
2023-07-31 10:51:57
不看后悔!揭秘游戏服务器开发
2023-08-22 16:20:30
![](https://img.aspxhome.com/file/2023/6/58306_0s.png)
javaweb页面附件、图片下载及打开(实现方法)
2023-11-25 05:33:44
详解SpringCloud mysql实现配置中心
2023-11-02 05:12:57
![](https://img.aspxhome.com/file/2023/8/58718_0s.png)
C语言malloc分配问题详解
2023-07-22 05:10:34
JAVA8 十大新特性详解
2023-07-02 10:03:27
synchronized背后的monitor锁实现详解
2023-07-31 08:14:10
vscode+platformIO开发stm32f4的实现
2023-11-02 16:43:37
![](https://img.aspxhome.com/file/2023/9/105169_0s.png)
C++实现LeetCode(2.两个数字相加)
2023-06-23 16:51:11
Flutter图片缓存管理ImageCache原理分析
2023-08-20 23:26:19
C#获取网页源代码的方法
2023-06-19 05:43:44
SpringBoot中整合MyBatis-Plus-Join使用联表查询的实现
2023-11-28 19:00:26
25行Java代码将普通图片转换为字符画图片和文本的实现
2023-11-24 02:04:26
![](https://img.aspxhome.com/file/2023/5/59855_0s.jpg)
Java Set集合的遍历及实现类的比较
2023-11-05 16:08:10
iOS新浪微博、腾讯微博分享功能实例
2023-06-16 09:15:53
![](https://img.aspxhome.com/file/2023/0/101960_0s.png)
Spring Boot 在启动时进行配置文件加解密的方法详解
2023-11-12 17:13:54
学习SpringBoot容器功能及注解原理
2023-11-24 22:06:17
![](https://img.aspxhome.com/file/2023/4/59044_0s.png)