Servlet WebSocket的简易聊天室
添加依赖
<!-- websocket -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>${websocket.version}</version>
<scope>provided</scope>
</dependency>
ChatServer后台类
package edu.nf.ws.server; import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Time;
import java.util.Date;
import java.util.Set; /**
* @Author Eric
* @Date 2018/12/5
* WebSocket服务端
*/
@ServerEndpoint("/chat/server/{userName}")
public class ChatServer {
/**
* 当有客户端连接到服务端的时候就会调用这个方法
* session代表客户端和服务端的一个连接会话对象,
* 由容器负责创建和维护
* @param session
* @param userName
*/
@OnOpen
public void onOpen(Session session,@PathParam("userName") String userName) throws UnsupportedEncodingException {
//userName=URLDecoder.decode(userName,"UTF-8");
System.out.println("有客户端连接..."+userName);
//将用户名保存到当前用户会话的属性中(有点类似作用域的概念)
session.getUserProperties().put("user",userName);
} /**
* 客户端和服务器之间通信的方法,
* 服务端每当接收客户端的消息就会调用这个方法
* 注意:必须制定一个String类型的参数,表示接收到客户的文本消息
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message,Session session) throws IOException {
System.out.println("接收消息..."+message);
//将消息发给所有人
sendAllUser(message,session);
} /**
* 当客户端关闭或者断开连接时,服务端会调用此方法
*/
@OnClose
public void onClose(Session session) throws IOException {
System.out.println("客户失去连接...");
session.close();
}
private void sendAllUser(String message,Session session) throws IOException {
//获取所有人的会话对象
Set<Session> users = session.getOpenSessions();
//获取发送人
String sendUser = session.getUserProperties().get("user").toString();
//发送给所有人
for (Session user : users) {
user.getBasicRemote().sendText(getTime()+"<br/>"+sendUser+":"+message);
}
}
private Time getTime(){
//创建当前时间
Date date = new Date();
Time time = new Time(date.getTime());
return time;
}
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简易对话</title>
</head>
<body>
<div id="login_div">
用户名:<input type="text" id="userName" name="userName"/>
<input type="button" id="login" value="login"/>
</div> <div id="container" style="display: none">
<div id="content"></div>
<input type="text" id="msg" name="msg"/>
<input type="button" id="send" value="send"/>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(function () {
var ws;
//登陆
$("#login").on("click",function () {
var userName = $("#userName").val();
//创建WebSocket对象并连接服务端
ws = new WebSocket('ws://localhost:8080/chat/server/'+userName);
//客户端打开连接时会回调此方法
/*ws.onopen = function(){
//...
}*/ //客户端关闭或断开连接时执行此方法
/*ws.onclose = function(){
//...
}*/
//接收服务端发送的信息
ws.onmessage =function (message) {
$("#content").append(message.data+"<br/>")
}
$('#login_div').css('display','none');
$('#container').css('display','block');
});
//发送信息
$("#send").on('click',function () {
var msg = $('#msg').val();
//发送消息
ws.send(msg);
});
});
</script>
</body>
</html>
Servlet WebSocket的简易聊天室的更多相关文章
- 基于Node.js + WebSocket 的简易聊天室
代码地址如下:http://www.demodashi.com/demo/13282.html Node.js聊天室运行说明 Node.js的本质就是运行在服务端的JavaScript.Node.js ...
- php+websocket搭建简易聊天室实践
1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...
- node.js+websocket实现简易聊天室
(文章是从我的个人主页上粘贴过来的,大家也可以访问我的主页 www.iwangzheng.com) websocket提供了一种全双工客户端服务器的异步通信方法,这种通信方法使用ws或者wss协议,可 ...
- node+websocket创建简易聊天室
关于websocket的介绍太多,在这就不一一介绍了,本文主要实现通过websocket创建一个简易聊天室,就是90年代那种聊天室 服务端 1.安装ws模块,uuid模块,ws是websocket模块 ...
- 使用Html5下WebSocket搭建简易聊天室
一.Html5WebSocket介绍 WebSocket protocol 是HTML5一种新的协议(protocol).它是实现了浏览器与服务器全双工通信(full-duplex). 现在,很多网站 ...
- WebSocket实现简易聊天室
前台页面: <html> <head> <meta http-equiv="Content-Type" content="text/html ...
- 小案例-WebSocket实现简易聊天室
前言 在详解 HTTP系列之一讲到HTTP/2.0 突破了传统的"请求-问答模式"这一局限,实现了服务器主动向客户端传送数据.而本章将通过一种在单个TCP连接上进行全双工通信的协议 ...
- 基于WebSocket的简易聊天室
用的是Flash + WebSocket 哦~ Flask 之 WebSocket 一.项目结构: 二.导入模块 pip3 install gevent-websocket 三.先来看一个一对一聊天的 ...
- 使用go,基于martini,和websocket开发简易聊天室
一.首先,需要了解一下websocket基本原理:here 二.go语言的websocket实现: 基于go语言的websocket也有不少,比如github.com/gorilla/websocke ...
随机推荐
- HDU 4614 Vases and Flowers(二分+线段树区间查询修改)
描述Alice is so popular that she can receive many flowers everyday. She has N vases numbered from 0 to ...
- jmeter简单压测设置
参数化 随机参数 时间参数 顺序自增函数 文件读取 直接引用 响应断言 用来查看sessionid 关联 关联引用 jmeter操作数据库 安装连接程序包 ip 端口号 哪个数据库 可以执行多条s ...
- [leetcode]300. Longest Increasing Subsequence最长递增子序列
Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Inp ...
- linux 备忘录
1. ps aux|grep 程序 -------->查看当前程序是否运行 ps aux|grep nginx 2. tar -zxvf 压缩包 ---------> 解压缩 tar -z ...
- sqlite c#
https://www.cnblogs.com/icebutterfly/p/7850689.html https://www.cnblogs.com/sdadx/p/7127098.html
- ROS与深度相机入门教程-在ROS使用kinect v1摄像头
ROS与深度相机入门教程-在ROS使用kinect v1摄像头 说明: 介绍在ros安装和使用kinect v1摄像头 介绍freenect包 安装驱动 deb安装 $ sudo apt-get in ...
- ROS安装
本文参考地址:http://ros.exbot.net/wiki/cn(2f)indigo(2f)Installation(2f)Ubuntu.html http://wiki.ros.org/ind ...
- Centos 7.0 Firewall-cmd 使用方式
开启端口命令 输入firewall-cmd --query-port=6379/tcp,如果返回结果为no,那么证明6379端口确实没有开启.输入firewall-cmd --add-port=637 ...
- VS2010错误
1.用VS2010生成C++程序时,链接器工具错误 LNK1123: fatal error LNK1123: failure during conversion to COFF: file inva ...
- Tinyos学习笔记(三)
读取Telosb内部传感器数据,并在计算机上显示. senseC.nc代码如下: #include "Timer.h" #include "sense.h" # ...