使用WebSocket实现多人实时聊天
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title> 使用WebSocket通信 </title>
- <script type="text/javascript">
- // 创建Web Socket对象
- var webSocket = new WebSocket("ws://127.0.0.1:30000");
- webSocket.onopen = function()
- {
- // 为onmessage事件绑定监听器,接收消息
- webSocket.onmessage= function(event)
- {
- // 接收、并显示消息
- document.getElementById('show').innerHTML
- += event.data + "<br/>";
- }
- };
- var sendMsg = function(val)
- {
- var inputElement = document.getElementById('msg');
- // 发送消息
- webSocket.send(inputElement.value);
- // 清空单行文本框
- inputElement.value = "";
- }
- </script>
- </head>
- <body>
- <div style="width:600px;height:240px;
- overflow-y:auto;border:1px solid #333;" id="show"></div>
- <input type="text" size="80" id="msg" name="msg"/>
- <input type="button" value="发送" οnclick="sendMsg();"/>
- </body>
- </html>
- import java.io.*;
- import java.net.*;
- import java.nio.charset.Charset;
- import java.security.MessageDigest;
- import java.util.regex.*;
- import java.util.*;
- import sun.misc.BASE64Encoder;
- /**
- * Description:
- * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
- * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
- * <br/>This program is protected by copyright laws.
- * <br/>Program Name:
- * <br/>Date:
- * @author Yeeku.H.Lee kongyeeku@163.com
- * @version 1.0
- */
- public class ChatServer
- {
- // 记录所有的客户端Soccket
- public static List<Socket> clientSockets
- = new ArrayList<Socket>();
- public ChatServer()throws IOException
- {
- // 创建ServerSocket,准备接受客户端连接
- ServerSocket ss = new ServerSocket(30000);
- while(true)
- {
- // 接收到客户端连接
- Socket socket = ss.accept();
- // 将客户端Socket添加到clientSockets集合中
- clientSockets.add(socket);
- // 启动线程
- new ServerThread(socket).start();
- }
- }
- public static void main(String[] args)
- throws Exception
- {
- new ChatServer();
- }
- }
- class ServerThread extends Thread
- {
- private Socket socket;
- public ServerThread(Socket socket)
- {
- this.socket = socket;
- }
- public void run()
- {
- try
- {
- // 得到Socket对应的输入流
- InputStream in = socket.getInputStream();
- // 得到Socket对应的输出流
- OutputStream out = socket.getOutputStream();
- byte[] buff = new byte[1024];
- String req = "";
- // 读取数据,此时建立与WebSocket的"握手"。
- int count = in.read(buff);
- // 如果读取的数据长度大于0
- if(count > 0)
- {
- // 将读取的数据转化为字符串
- req = new String(buff , 0 , count);
- System.out.println("握手请求:" + req);
- // 获取WebSocket的key
- String secKey = getSecWebSocketKey(req);
- System.out.println("secKey = " + secKey);
- String response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: "
- + "websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "
- + getSecWebSocketAccept(secKey) + "\r\n\r\n";
- System.out.println("secAccept = " + getSecWebSocketAccept(secKey));
- out.write(response.getBytes());
- }
- int hasRead = 0;
- // 不断读取WebSocket发送过来的数据
- while((hasRead = in.read(buff)) > 0)
- {
- System.out.println("接收的字节数:" + hasRead);
- /*
- 因为WebSocket发送过来的数据遵循了一定的协议格式,
- 其中第3个~第6个字节是数据掩码。
- 从第7个字节开始才是真正的有效数据。
- 因此程序使用第3个~第6个字节对后面的数据进行了处理
- */
- for (int i = 0 ; i < hasRead - 6 ; i++ )
- {
- buff[i + 6] = (byte) (buff[i % 4 + 2] ^ buff[i + 6]);
- }
- // 获得从浏览器发送过来的数据
- String pushMsg = new String(buff
- , 6 , hasRead - 6 , "UTF-8");
- // 遍历Socket集合,依次向每个Socket发送数据
- for (Iterator<Socket> it = ChatServer.clientSockets.iterator()
- ; it.hasNext() ;)
- {
- try
- {
- Socket s = it.next();
- // 发送数据时,第一个字节必须与读到的第一个字节相同
- byte[] pushHead = new byte[2];
- pushHead[0] = buff[0];
- // 发送数据时,第二个字节记录发送数据的长度
- pushHead[1] = (byte) pushMsg.getBytes("UTF-8").length;
- // 发送前两个字节
- s.getOutputStream().write(pushHead);
- // 发送有效数据
- s.getOutputStream().write(pushMsg.getBytes("UTF-8"));
- }
- catch (SocketException ex)
- {
- // 如果捕捉到异常,表明该Socket已经关闭
- // 将该Socket从Socket集合中删除
- it.remove();
- }
- }
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- // 关闭Socket
- socket.close();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- }
- }
- // 获取WebSocket请求的SecKey
- private String getSecWebSocketKey(String req)
- {
- //构建正则表达式,获取Sec-WebSocket-Key: 后面的内容
- Pattern p = Pattern.compile("^(Sec-WebSocket-Key:).+",
- Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
- Matcher m = p.matcher(req);
- if (m.find())
- {
- // 提取Sec-WebSocket-Key
- String foundstring = m.group();
- return foundstring.split(":")[1].trim();
- }
- else
- {
- return null;
- }
- }
- // 根据WebSocket请求的SecKey计算SecAccept
- private String getSecWebSocketAccept(String key)
- throws Exception
- {
- String guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
- key += guid;
- MessageDigest md = MessageDigest.getInstance("SHA-1");
- md.update(key.getBytes("ISO-8859-1") , 0 , key.length());
- byte[] sha1Hash = md.digest();
- BASE64Encoder encoder = new BASE64Encoder();
- return encoder.encode(sha1Hash);
- }
- }
使用WebSocket实现多人实时聊天相关推荐
- springboot+websocket+layui制作的实时聊天室,后端开发入门样例
实时聊天室 前言 效果图 涉及技术 springboot layui websocket 实现思路 websocket在springboot下的实现 前端实现 建立websocket连接 前端对应的w ...
- 利用websocket+Vuex完成一个实时聊天软件(前端部分)
文章目录 前言 一.效果如图 二.具体实现步骤 1.引入Vuex 2.webscoked实现 总结 前言 这篇文章主要利用websocked 建立长连接,利用Vuex全局通信的特性,以及watch,c ...
- websocket实现多用户一对一实时聊天
在线聊天模实现 项目是基于node.js服务器搭建的简易双向通信网页,实现了实时更新在线人数以及用户间即时通讯的功能. 1.websocket连接创建 基于后台websocket地址创建简易的连接,并 ...
- WebSocket实现多人在线聊天功能
WebSocket是现在最流行的实现多人在线聊或者私聊的技术,它可以实现客户端到客户端的通信,和以往的TCP和UDP不一样,它俩是客户端到服务端的通信,而且服务端不能直接给客户端发送消息,但是WebS ...
- Python+django网页设计入门(20):使用WebSocket创建多人在线聊天室
2019年3月8日-10日公众号送书活动:中小学生Python课应该学什么 ================ 前导课程: Python+django网页设计入门(19):创建新模型扩展自带用户表的字段 ...
- 【java IO流项目】实现多人实时聊天室,需连接同一WiFi
想要完成这个项目的前提条件 ①多个人连接同一WiFi在局域网里,所有人关闭防火墙,就使用中的,不会就关闭所有 ②指定一个人为服务端 ,这个人去命令行ipconfig查看自己的ipv4 这是我win11 ...
- 【nodejs实打造多人实时聊天室】
server.js文件 // 加载net模块 var net = require("net"); // 创建net实例对象 var server = net.createServe ...
- 【详解】springboot 集成 websocket实现网页版实时聊天
1.application.yml 配置文件 server:port: 8080spring:thymeleaf:prefix: classpath:/view/suffix: .htmlencodi ...
- 网页实时聊天之PHP如何实现websocket
网页实时聊天之PHP如何实现websocket 一.总结 一句话总结: 应用 PHP 的 socket 函数库:PHP 的 socket 函数库跟 C 语言的 socket 函数非常类似 PHP 实现 ...
- websocket 西部数码php_网页实时聊天之PHP实现websocket
前言 websocket 作为 HTML5 里一个新的特性一直很受人关注,因为它真的非常酷,打破了 http "请求-响应"的常规思维,实现了服务器向客户端主动推送消息,本文介绍如 ...
最新文章
- mysql5.6英文版安装步骤_mysql5.6版本安装步骤详解
- salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type)...
- c++ primer 习题13.39自己做的答案
- DBCP针对不同数据库的validationQuery
- 庖丁解牛TLD(三)——算法初始化
- Java 的布局管理器GridBagLayout的使用方法【图文说明】
- Hadoop生态圈-Flume的组件之sink处理器
- Cowrie 部署 SSH 蜜罐
- CAD图纸可以约束转换后图纸格式的大小吗?
- 三星android版本升级包下载,三星oneui3.0系统
- Java中BigDecimal用法
- ssh: connect to host github.com port 22: Connection refused
- 网页崩溃原因软件测试,让Web站点崩溃最常见的七大原因
- JAVA模拟扑克牌洗牌发牌
- 1168: PIPI的方格
- 【补充习题七】积分不等式及定积分性质
- 英特尔CPU详细参数表(新老CPU详细对照表)
- Nginx通过OpenSSL创建自签名证书配置HTTPS及二级目录
- NISP二级证书换CISP证书是怎么回事?
- 工作无聊?程序员上班没事做该怎么办!
热门文章
- mac/macbook触摸板/鼠标/键盘失灵
- 如何对NTFS文件进行压缩和加密
- matlab特定颜色提取
- java数字签名实现简单的动态秘钥
- C语言理论小学案例试讲,【精选】C语言试讲 演示文稿C语言试讲 演示文稿.ppt
- 基于单片机门电路测试
- ACM ICPC 2008–2009 NEERC MSC A, B, C, G, L
- 从C到C++___类继承(五)多重继承
- 安兔兔:2018年8月iOS设备性能排行榜
- 电信光纤猫与无线路由器连接