html5 chat,HTML5 Real-Time Chat with Websockets, jQuery, and Spike-Engine

Introduction

Everything in the web becomes increasingly real-time and HTML5 finally offers some facilities to build efficient, simple and robust real-time applications on the web. This article serves as a demonstration of such facilities in building a fun and simple client-server chat:

It uses websocketsinternally, but abstracted by Spike-Engine, will fallback to flash sockets for older browsers.

It uses HTML5 Data URI for rendering images streamed from the server as byte arrays.

It uses custom fonts and jQuery for animated rendering.

It is cross-platform and with a minimized packet payload and message compression.

The application server is a self-hosted executable and the client is just a plain html file.

demo.png

Client-Server Protocol

First of all, we need to define a communication protocol between. This represents the messages which are exchanged between the client and the server. Spike-Engine simplifies the networking implementation and allows expressing this protocol declaratively via an XML file. This part is quite straightforward, check the user guide on their website for more info.

XML

Copy Code

Essentially, we've declared 3 message types:

JoinMyChat: initiated by the client who wants to join the chat room. Server will add the client to the room (a list of clients) and generate an identicon to be used as an avatar for that client.

SendMyChatMessage: initiated by the client and contains a string message to send to everyone in the chat room.

MyChatMessages: initiated by the server, sends the avatar and the message to everyone in the room. This is an event of type push, it is pushed to the clients. More info: http://en.wikipedia.org/wiki/Push_technology

Because we are using Spike-Engine to abstract our websockets/flashsockets communication, the network layer is automatically generated, similarly to web services. I won't go into the code generation part here, as a step-by-step explanation can be found here: http://www.spike-engine.com/manual-client and is out of the scope of this article.

Identicons and HTML5 Data URI

In our chat application, I wanted to use avatars, but I didn't want the users to log-in or chose one, it had to be automatically generated. But not randomly, same IP address should have the same avatar, identifying the person even if he disconnects/reconnects or uses a different computer to chat. Identiconsare the right answer for that job.  An Identicon is a visual representation of a hash value, usually of an IP address, that serves to identify a user of a computer system as a form of avatar while protecting the users' privacy.

f669b563746e081f0a9cf0160b5aea10.png

How to generate them? Jeff Atwood, from stackoverflow wrote a port of such library: http://www.codinghorror.com/blog/2007/01/identicons-for-net.html. And I used their open-sourced library to do this: http://identicon.codeplex.com, with some small alterations. The rendering is straightforward.

C#

Copy Code

public byte[] Render(IClient client)

{

using (var stream = new MemoryStream())

{

//Get the code from the ip address

var code = IdenticonUtil.Code(client.Channel.Address.ToString());

//Generate the identicon

var image = this.Render(code, 50);

//Save as png

image.Save(stream, ImageFormat.Png);

return stream.ToArray();

}

}

The interesting part is that on each message, we want to send the avatar of the user, represented as a byte[]. But how do we actually render it once the JavaScript client received the array? The answer is the new HTML5 feature called Data URI.

"The data URI scheme is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources. This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient." - From Wikipedia's entry on Data URI.

The following code snipped shows how we render the byte array received by javascript and convert it to a data uri. The final step is just assigning that URI to an element.

JavaScript

Copy Code

//Get the bytes of the image and convert it to a BASE64 encoded string and then

//we use data URI to add dynamically the image data

var avatarUri = "data:image/png;base64," + avatar.toBase64();

Appendix A: Server-Side Implementation

For the sake of completeness of this article, here is the full server-side implementation of the chat, exluding the identicon file.

C#

Copy Code

public static class MyChatImpl

{

/// ///A public static function, when decorated with InvokeAt attribute will be ///invoked automatically by Spike Engine. This particular one will be invoked ///when the server is initializing (only once). /// [InvokeAt(InvokeAtType.Initialize)]

public static void Initialize()

{

//First we need to hook the events while the server is initializing,

//giving us the ability to listen on those events.

MyChatProtocol.JoinMyChat += new RequestHandler(OnJoinChat);

MyChatProtocol.SendMyChatMessage += new RequestHandler(OnSendMessage);

//Since we will add the clients in the chat, we need to remove them from

//the chat room once they are disconnected.

Service.ClientDisconnect += new ClientDisconnectEventHandler(OnClientDisconnect);

}

/// ///A list of all clients currently in the chat. This is a concurrent list that ///helps us to avoid most of the concurrency issues as many clients could be ///added/removed to the list simultaneously. /// public static ConcurrentList PeopleInChat = new ConcurrentList();

/// ///Static method that is ivoked when a client sends a message to the server. /// static void OnSendMessage(IClient client, SendMyChatMessageRequest packet)

{

//Validate the message

var message = packet.Message;

if (message == null || message == String.Empty || message.Length > 120)

return;

//We loop through all people in the chat and we broadcast them

//the incoming message.

foreach (var person in PeopleInChat)

{

//Send the message now

person.SendMyChatMessagesInform(

(byte[])client["Avatar"], //The avatar of the client who sends the message

message //The message to be sent

);

}

}

/// ///Static method that is ivoked when a client decides to join the chat. /// static void OnJoinChat(IClient client)

{

//We add the person to the chat room

if (!PeopleInChat.Contains(client))

{

//Generate the avatar for the client

client["Avatar"] = IdenticonRenderer.Create(client);

//Add the person in the room

PeopleInChat.Add(client);

//Say something nice

SayTo(client, "Hi, I'm the author of this sample, hope you like it!

Just type a message below and see how it works on CodeProject.");

}

}

/// ///Static method that is invoked when a client is disconnected. /// static void OnClientDisconnect(ClientDisconnectEventArgs e)

{

//Remove the client from the list if he's

//disconnected from the chat

if (PeopleInChat.Contains(e.Client))

PeopleInChat.Remove(e.Client);

}

/// ///Author says something to a particular client in the chat room. /// static void SayTo(IClient client, string message)

{

client.SendMyChatMessagesInform(Resources.Author, message);

}

}

Appendix B: Client-Side Implementation

The client-side implementation is a bit more tricky, as there's some JQuery for visualisation and css files. Everything is included in the source package attached to this codeproject article.

JavaScript

Copy Code

var bubbles = 1;

var maxBubbles = 8;

var server;

function sendMessage() {

server.sendMyChatMessage($("#msgText").val());

$("#msgText").val("");

}

function addBubble(avatar, text) {

//Get the bytes of the image and convert it to a BASE64 encoded string and then

//we use data URI to add dynamically the image data

var avatarUri = "data:image/png;base64," + avatar.toBase64();

var bubble = $('

'class="bubble">p><p>avatarUri%20+%20'

' + text +

'

');

$("#msgText").val("");

$(".bubble-container:last")

.after(bubble);

if (bubbles >= maxBubbles) {

var first = $(".bubble-container:first")

.remove();

bubbles--;

}

bubbles++;

$('.bubble-container').show(250, function showNext() {

if (!($(this).is(":visible"))) {

bubbles++;

}

$(this).next(".bubble-container")

.show(250, showNext);

$("#wrapper").scrollTop(9999999);

});

}

//On page loaded and ready

$(window).load(function () {

//First we need to create a server channel on the given URI, in a form http://IP:PORT

//For your local test you might try http://127.0.0.1:8002 (or a different IP address/port)

server = new spike.ServerChannel('http://127.0.0.1:8002');

//When the browser is connected to the server, we show that we are connected to the user

//and provide a transport name (websockets, flashsockets etc.).

server.on('connect', function () {

//Once connected, we need to join the chat

server.joinMyChat();

});

//Here we hook the room messages inform event so we know when

//the server sends us the messages. We need to show them properly in the text area.

server.on('myChatMessagesInform', function (p) {

addBubble(p.avatar, p.message);

});

});

History

23/06/2015 - Source code & article updated to Spike v3

14/09/2013 - Updated source code references & links.

16/08/2013 - Live demo link.

15/08/2013 - Initial article.

H5+即时通讯功能实现:图片、语音与表情的聊天体验 -- 这是一个uni-app框架的页面结构 --><button @click="clickHandler">点击我</button> 阅读详情

相关推荐

html5+css+mui chat聊天窗口聊天气泡 调用相机 手机图册 聊天表情

html5+css+mui chat聊天窗口聊天气泡 支持调用相机 支持手机图册 聊天表情 支持聊天气泡宽度根据文字长度进行自适应 美观大方

纯代码创建一个H5多人聊天室

现在,你可以在不同的浏览器窗口中打开该HTML文件,它们将通过服务器进行实时的多人聊天。在前端,你可以使用HTML、CSS和JavaScript来构建用户界面和实现聊天功能。在后端,你需要选择一种服务器端技术(如Node.js)来处理客户端的连接和消息传递。请注意,这只是一个简单的示例,用于演示如何使用WebSocket和Node.js创建多人聊天室。在实际开发中,你可能需要添加更多的功能和安全性措施,如用户认证、消息过滤等。如需更复杂的功能或更高级的安全性,你可能需要进一步学习和研究相关技术。

KGH2023的博客 1424

h5仿wechat聊天框架

只有CSS+html+jquery代码,非常简洁,实际项目使用过,一块一块代码复制粘贴即可,很简单实用

h5聊天页面 jquery_h5聊天室web端(仿微博、微信)|h5仿微信网页端|仿微信界面弹窗...

/*--- 用户设置.Start ---*///联系人/群聊切换$("body").on("click", ".wc__addChat-tab li", function() {var idx = $(this).index();$(this).addClass("on").siblings().removeClass("on");$(this).parents(".wc__popupTmpl")...

weixin_32532029的博客 1209

wechat-h5-boilerplate-master

微信h5小程序的一个通用框架,目前在晚上当中,有问题的m

MyGauge.zip 使用ChartJS和Spike-Engine的實時儀表

使用ChartJS和Spike-Engine的實時儀表 網絡中的所有內容都變得越來越實時,HTML5最終提供了一些功能,可以在網絡上構建高效,簡單和健壯的實時應用程序。 本文演示瞭如何構建儀表,這些儀表每秒實時更新5次,可用於服務器監控或構建儀表板:

JS+H5在线文心AI聊天(第三方接口)

调用文心接口聊天

w11111xxxl的博客 1013

科技中介服务机构想要提升服务效率,需要哪些数智工具支持?.docx

科技中介服务机构想要提升服务效率,需要哪些数智工具支持?

移动端h5聊天室布局

h5聊天

weixin_43550562的博客 1316

SpikeEngine:这是一个可以在烤面包机上运行的游戏引擎!

穗 欢迎使用Spike的源代码 这是一个游戏引擎 寻找如何在系统上设置Spike? 就! 突击行动 产品特点 状态 控制台记录 :check_mark: 完成了 内部键和鼠标代码 :check_mark: 完成了 输入轮询 :check_mark: 完成了 LayerStack和图层 :check_mark: 完成了 活动系统和活动 :check_mark: 完成了 2D渲染器 :check_mark: 完成了 实体组件系统(ECS) :check_mark: 完成了 C#脚本 :check_mark: 完成了 GUI编辑器(尖峰编辑器) :check_mark: 完成了 场景序列化和反序列化 :check_mark: 完成了 Gizmos控制对象的变换 :check_mark: 完成了 内置开发者控制台 :check_mark: 完成了 编辑相机 :check_mark: 完成了 2D物理 :check_mark: 完成了 使用反照率加

AI工具如何提升产品经理工作效率

AI工具在现代产品管理中扮演着越来越重要的角色,从需求挖掘到原型设计再到交付物制作,AI技术正在重塑产品经理的工作流程。通过自然语言处理(NLP)和机器学习(ML)技术,AI工具能够自动化处理大量重复性任务,如用户访谈转录、竞品分析、原型生成等,显著提升工作效率。以ChatGPT和Notion AI为例,这些工具可以快速生成结构化分析框架和PRD初稿,将传统需要数小时甚至数天的工作压缩到几分钟内完成。在产品设计阶段,工具如Uizard和Galileo AI能够根据文本描述自动生成可交互原型,大幅缩短设计探索

weixin_29194817的博客 242

关于 H5 聊天应用的几点小建议

H5 聊天应用讲解

GitChat 632

sentaurus学习笔记(HFET_pGate_GaN仿真)(九)

`(sdedr:define-constant-profile-placement "Ohmic.s" "Ohmic" "Pl.ohmic.s" 0.002)`这一行将`"Ohmic"`掺杂剖面放置在`"Pl.ohmic.s"`参考评估窗口中,同样`0.002`可能表示掺杂剖面在窗口中的偏移量或其他参数。欧姆接触是半导体器件中的一种低阻抗电气接触,通常需要高掺杂来减少接触电阻并提高器件性能。通过这些步骤,SDE能够为器件的源极和漏极区域设置高掺杂的欧姆接触,这对于确保器件的高性能和低接触电阻至关重要。

qq_52640792的博客 1382

基于java的HTML5实时聊天工具系统设计与实现

基于Java的HTML5实时聊天工具系统设计与实现的系统性能评估的总结和分析如下:1.并发性能评估通过模拟多个用户同时进行操作,评估系统的并发性能。可以观察到,在处理大量的并发请求时,系统出现了明显的性能瓶颈。通过分析日志,发现是由于系统缓存过期导致的,因此需要对缓存策略进行优化。同时,还需要对数据库连接池进行优化,以提高系统性能。2.响应速度评估通过测试不同功能的响应时间,可以观察到系统的响应速度存在一定的延迟。经过分析,发现是由于系统缓存过期导致的,因此需要对缓存策略进行优化。

m0_62396648的博客 1263

【GAN实战】基于pytorch-CycleGAN与pix2pix的自定义数据集训练全攻略

本文详细解析了基于PyTorch的CycleGAN与pix2pix模型在自定义数据集上的完整训练流程。核心在于根据数据是否成对来正确选择模型:pix2pix适用于严格配对的“孪生”数据,而CycleGAN则擅长处理非配对的“散装”数据集。文章从数据准备、配置训练到测试应用,提供了全链路实战指南与关键参数调优心得,帮助开发者高效实现图像到图像的风格转换。

x2y3z4a5b的博客 704

【BUG已解决】pip install 出现 error: Microsoft Visual C++ 14.0 or greater is required 解决方案

方案磁盘占用适用场景推荐指数安装Build Tools3-6GB长期Windows Python开发⭐⭐⭐⭐⭐寻找预编译wheel无额外占用只是想快速装上某个包⭐⭐⭐⭐⭐用conda安装视包而定已经在用conda环境⭐⭐⭐⭐⭐升级到新版本无额外占用库本身有更新的预编译版本⭐⭐⭐⭐使用WSL2需要额外配置Linux子系统频繁遇到Windows编译问题⭐⭐⭐⭐的核心是Windows 缺少本地 C/C++ 编译器,而目标包需要在本机编译。先看是否有捷径。

博客 1万+

HTML5 Chart.js 框架

HTML5 Chart.js 框架 版权声明:未经博主授权,内容严禁转载 ! Chart.js 概述: chart.js 是一个简单的、面向对象、为设计者开发者准备的图表绘制工具。 点击进入官方网址      chart.js 的特点 基于 HTML5   chart.js 基于 HTML5 canvas 技术,支持所有主流浏览器。   针对 IE7/IE8...

weixin_30367873的博客 282

Codex 100个真实案例 - 用AI自动生成API测试用例(接口测试全覆盖)

API 测试是保障后端质量的关键环节,但手写测试用例既枯燥又容易遗漏。本案例将展示如何用 Codex 从 Swagger/OpenAPI 规范文档自动生成 pytest 测试用例——包括正常流程测试、边界值测试、异常参数测试、性能压力测试,还能自动生成 Mock 数据和精美的 HTML 测试报告。全程自然语言驱动,让 API 测试覆盖率从 0 飙到 90%+!

yueyeguzhuo的专栏 271

h5聊天室案例|仿微信聊天界面|多人群聊

html5仿微信聊天室weChatRoom案例|多人群聊互动|仿微信聊天界面 该项目是使用html5+css3+zepto+swiper+wcPop等技术开发的仿微信聊天室,捣鼓调试了很长时间,在手机上已经适配各个设备,采用的是iphone6的750px屏宽加上css3里的flex伸缩布局,该聊天项目用到的各种弹窗效果则是自己专门为聊天项目开发的wcPop插件(仿微信弹窗效果、android...

码农ICoding 2万+

G.6 PaddleHub实战篇{ERNIE实现文新闻本分类、ERNIE3.0 实现序列标注}【四】

百度飞桨:ERNIE 3.0 、通用信息抽取 UIE、paddleNLP的安装使用[一]_汀、的博客-优快云博客PaddleHub--飞桨预训练模型应用工具{风格迁移模型、词法分析情感分析、Fine-tune API微调}【一】_汀、的博客-优快云博客 PaddleHub--{超参优化AutoDL Finetuner}【二】_汀、的博客-优快云博客PaddleHub实战篇{词法分析模型LAC、情感分类ERNIE Tiny}训练、部署【三】_汀、的博客-优快云博客通过前面几篇文章大家都有一定了解,下面

丨汀、的博客 6186

航空电子系统标准全景图:ARP4754A、ARP4761、DO-178C、DO-254 的协同作用

通过 ARP4754A、ARP4761、DO-178C 和 DO-254 的相互配合,确保航空电子系统的安全性和功能性在开发过程中得到充分保障。每一个文件在不同层面发挥作用,共同构成了一个完整的、系统的开发和验证框架,确保航空电子设备达到适航要求。这些标准不仅帮助开发人员有条理地开发复杂的航空系统,还确保所有系统组件(软件和硬件)在整个生命周期内都能满足最严格的安全和可靠性要求。

qq_41854911的博客 1812

h5仿微信聊天室weChatRoom|仿微信聊天界面

html5仿微信聊天|h5仿微信聊天室|仿微信聊天界面|仿微信群聊/单聊平时一闲下来就撸项目代码,最近一直在开发h5仿微信聊天项目,使用到了html5+css3+zepto+iscroll+swiper+wcPop等技术进行架构开发,整体页面采用750px适配,加上伸缩flex布局。 h5仿微信聊天实战项目,实现了消息、表情(动图)发送...

weixin_33953384的博客 3971

ISMN数据处理

可批量下载,十分方便

m0_46268055的博客 1216

H5+MUI+Node.js+Socket.io实现即时聊天以及发送+图片压缩+图片预览保存

H5+MUI+Node.js+Socket.io实现即时聊天以及发送+图片压缩+图片预览保存,可以做成长按图片保存,这里是点击按钮保存的。

云上人间钦自赏 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

h5聊天室效果

先写聊天室结构 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Co...

zheng_li_dong的博客 2065

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

上一篇: 微型计算机硬件组,微型计算机的硬件组的成.doc
下一篇: 浙大计算机考英语几,双非跨考浙大计算机详细经验分享
张小生blingbling
博客等级 码龄6年 43粉丝 87原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值