The content of this article is about how to create a webSocket web chat room in Java (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is webSocket
WebSocket is a network communication protocol and a persistence protocol. RFC6455 defines its communication standard.
WebSocket is a protocol for full-duplex communication on a single TCP connection that HTML5 began to provide.
2. Why use webSocket
Traditional web communication uses http technology. The http protocol is a stateless, connectionless, one-way application layer protocol. A request can only correspond to one response. Communication requests can only be issued by the client, and the server responds to the request. Therefore, the server is very passive in sending responses. This passive response is doomed to the fact that the server cannot proactively push responses to the client in a timely manner. If the server has continuous status changes, it will be very difficult for the client to obtain it. By frequently using asynchronous ajax to continuously obtain requests to implement long polling, this is particularly performance consuming and inefficient. (Keep shaking hands, or keep living for a long time).
And webSocket allows full-duplex communication between the server and the client. As long as the connection is established once, the connection can be maintained. Once a connection is established, both parties can communicate with each other without the need for multiple handshakes.
3. Implement WEB chat room
Add pom.xml and introduce jar package
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>
2. Create html and js file
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在线聊天室</title> <script type="text/javascript" src="./static/jquery-3.2.0.min.js"></script> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div> <div><span>聊天室</span> <button class="btn btn-warning" onclick="doClose();">退出聊天</button> </div> <div><textarea class="form-control" style="width: 40%;" rows="3" id="contentInp"></textarea></div><hr/> <div><button class="btn btn-danger" onclick="doClear();">清空会话框</button></div> <div id="content">开始聊天<br/></div> </div> </body> <script type="text/javascript"> var ws = new WebSocket("ws://localhost:8080/ws/websocket"); //controller层url $(function(){ $("#contentInp").keyup(function(evt){ if(evt.which == 13){ //enter键发送消息 var htm = $("#contentInp").val(); doSend(htm); $("textarea").empty(); } }); }) ws.onopen = function(){ appendHtm("连接成功!"); } // 从服务端接收到消息,将消息回显到聊天记录区 ws.onmessage = function(evt){ appendHtm(evt.data); } ws.onerror = function(){ appendHtm("连接失败!"); } ws.onclose = function(){ appendHtm("连接关闭!"); } function appendHtm(htm){ ($("#content")[0]).innerHTML += htm +"<br/>" } // 注销登录 function doClose(){ ws.close(); } // 发送消息 function doSend(htm){ // ($("#content")[0]).innerHTML += htm +"<br/>" ws.send(htm); } function doClear(){ $("#content").empty(); } </script> </html>
3.Backend java code
package controller; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.net.ssl.SSLSession; 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; @ServerEndpoint("/websocket") public class WebScoketServer { private static Integer onlineNum = 0; //当前在线人数,线程必须设计成安全的 private static CopyOnWriteArraySet<WebScoketServer> arraySet = new CopyOnWriteArraySet<WebScoketServer>(); //存放每一个客户的的WebScoketServer对象,线程安全 private Session session; /** * 连接成功 * @param session 会话信息 */ @OnOpen public void onOpen(Session session) { this.session =session; arraySet.add(this); this.addOnlineNum(); System.out.println("有一个新连接加入,当前在线 "+this.getOnLineNum()+" 人"); } /** * 连接关闭 */ @OnClose public void onClose() { arraySet.remove(this); this.subOnlineNum(); System.out.println("有一个连接断开,当前在线 "+this.getOnLineNum()+" 人"); } /** * 连接错误 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.err.println("发生错误!"); error.printStackTrace(); } /** * 发送消息,不加注解,自己选择实现 * @param msg * @throws IOException */ public void onSend(String msg) throws IOException { this.session.getBasicRemote().sendText(msg); } /** * 收到客户端消息回调方法 * @param session * @param msg */ @OnMessage public void onMessage(Session session, String msg) { System.out.println("消息监控:"+msg); for (WebScoketServer webScoketServer : arraySet) { try { webScoketServer.onSend(msg); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 增加一个在线人数 */ private synchronized void addOnlineNum() { onlineNum++; } /** * 减少一个在线人数 */ private synchronized void subOnlineNum() { onlineNum--; } private Integer getOnLineNum() { return onlineNum; } }
The above is the detailed content of How to create a webSocket web chat room in Java (with code). For more information, please follow other related articles on the PHP Chinese website!

一、什么是websocket接口使用websocket建立长连接,服务端和客户端可以互相通信,服务端只要有数据更新,就可以主动推给客户端。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocketAPI中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。在WebSocketAPI中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

在近几年的互联网应用中,Websocket已经成为了一种非常重要的通信协议。ThinkPHP6作为一款优秀的PHP开发框架,也提供了对Websocket的支持。不过,在使用Websocket时,我们通常会涉及到跨域、负载均衡等问题,因此,在这篇文章中,我们将介绍如何在ThinkPHP6中使用Nginx反向代理Websocket。首先,我们需要明确一下Webs

近年来,WebSocket技术日渐流行,成为了浏览器与服务器之间进行实时通信的标准选择。在Python中,我们可以通过一些成熟的库来实现WebSocket服务端的开发。本文将在介绍WebSocket技术的基础上,探索如何利用Python开发WebSocket服务端。一、什么是WebSocketWebSocket是一种在单个TCP

1、引入依赖org.springframework.bootspring-boot-starter-websocketorg.projectlomboklombokcom.alibabafastjson1.2.32、WebSocketConfig开启WebSocketpackagecom.shucha.deveiface.web.config;/***@authortqf*@Description*@Version1.0*@since2022-04-1215:35*/importorg.spri

许多应用程序,如游戏和直播等场景,需要一种机制来尽可能快地发送消息,同时可以接受无序、不可靠的数据传输方式。本机应用程序虽然可以使用原始 UDP 套接字,但这些在 Web 上不可用,因为它们缺乏加密、拥塞控制、同意发送机制(以防止 DDoS 攻击)。

随着现代网络应用程序的增多,WebSocket技术也变得非常流行。它是一项基于TCP协议的长连接技术,可以在客户端和服务器之间创建双向通信管道。在本文中,我们将介绍如何在Linux系统中使用WebSocket技术来创建一个简单的实时聊天应用程序。一、安装Node.js要使用WebSocket,首先需要在Linux系统中安装Node.j

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了怎么使用php原生socket实现一个简易的web聊天室?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

在现代Web应用程序开发中,WebSocket是实现即时通信和实时数据传输的常用技术。SpringBoot框架提供了集成WebSocket的支持,使得开发者可以非常方便地实现推送和通知功能。本文将介绍SpringBoot中如何使用WebSocket实现推送和通知功能,并演示一个简单的实时在线聊天室的实现。创建SpringBoot项目首先,我们需要创建一


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
