socket.io 多聊天室用于手机app聊天是不是有点大

安装好环境,请参考&和&&。
服务器端的搭建参考官网,里面有非常详细的描述,按照步骤下来,最终可以在localhost进行模拟聊天。
下面是手机端的说明。
引入socket.io.js:
&script src="js/socket.io.js"&&/script&
定义Chats tab:
&!-- Chats Tab --&
&ion-tab title="Chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/chats"&
&ion-nav-view name="tab-chats"&&/ion-nav-view&
&/ion-tab&
&定义tab-chat.html:
&ion-view view-title="Chats"&
&ion-content overflow-scroll="true" style="overflow: hidden"&
&ion-scroll zooming="true" direction="y" style=" height:500" &
&ion-list&
&uib-alert ng-repeat="msgInfo in messages" type="{{msgInfo.type}}" close="closeAlert($index)"&{{msgInfo.msgType}}: {{msgInfo.msg}}&/uib-alert&
&/ion-list&
&/ion-scroll&
&div class="bar bar-footer"&
&label class="item item-input" style=" width:85%"&
&input type="text" placeholder="please add your message here" ng-model="msg"&&/input&
&button class="button button-positive" ng-click="send(msg)"&Send&/button&
&/ion-content&
&/ion-view&
&在app.js中定义chats的state:
.state('tab.chats', {
url: '/chats',
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
&定义ChatsCtrl:
.controller('ChatsCtrl', function ($scope,mediaPlayer, chats) {
$scope.messages = [];
chats.on('chat message', function (msg) {
var msgInfo = { msg: msg, type: 'warning',msgType:"Receiver" }
$scope.messages.push(msgInfo);
console.log('receive msg from others: ' + msg);
$scope.send = function (msg) {
var msgInfo = { msg: msg, type: 'success', msgType: "Sender" }
$scope.messages.push(msgInfo);
console.log('start to send msg: ' + msg);
chats.emit('chat message', msg);
$scope.closeAlert = function (index) {
$scope.messages.splice(index, 1);
&实现factory:
var baseUrl = 'http://localhost:3000/';
.factory('chats', function socket($rootScope) {
var socket = io.connect(baseUrl);
on: function (eventName, callback) {
socket.on(eventName, function () {
var args =
$rootScope.$apply(function () {
callback.apply(socket, args);
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args =
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
参考资料:
/jbavari/ionic-socket.io-redis-chat
http://jbavari.github.io/blog//building-a-chat-client-with-ionic/
http://socket.io/get-started/chat/
阅读(...) 评论()每多学一点知识,就少写一行代码。
转载请注明 & 源代码&:ShuangMuChengLi/chat-socket.io.git英文原文 && demo演示& Get Started: Chat applicationIn this guide we’ll create a basic chat application. It requires almost no basic prior knowledge of Node.JS or Socket.IO, so it’s ideal for users of all knowledge levels.开始:聊天应用在这个教程,我们将创建一个基本的聊天应用。它几乎不需要前置基础的Node.js或者Socket.IO知识,所以它适合所有知识层次的用户人群。IntroductionWriting a chat application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it’s a lot slower than it should be.Sockets have traditionally been the solution around which most realtime chat systems are architected, providing a bi-directional communication channel between a client and a server.This means that the server can&push&messages to clients. Whenever you write a chat message, the idea is that the server will get it and push it to all other connected clients.介绍使用LAMP(PHP)那样的流行的web应用写一个聊天应用通常是很难的。它包含轮询服务器的变化,记录时间戳,并且它比实际会慢很多。Sockets 通常作为大多数实时聊天系统的解决方案被架构,提供一个连接服务器和客户端的双向通讯通道。这个意味着服务器能够推送消息到客户端。当你写一个聊天消息,服务器将获取它,并且推送它到所有的连接着的客户端。The web frameworkThe first goal is to setup a simple HTML webpage that serves out a form and a list of messages. We’re going to use the Node.JS web framework&express&to this end. Make sure&.First let’s create a&package.json&manifest file that describes our project. I recommend you place it in a dedicated empty directory (I’ll call mine&chat-example).web框架第一步是设置一个简单的HTML页面,提供一个表单和一个消息列表。为此,我们将使用Node.JS的express框架。请确保已经安装.首先,我们创建package.json清单文件,描述我们的项目。我建议你将它置于一个专用的空的文件夹中(称为chat-example){
&&&name&:&&socket-chat-example&,
&&&version&:&&0.0.1&,
&&&description&:&&my&first&socket.io&app&,
&&&dependencies&:&{}
}Now, in order to easily populate the&dependencies&with the things we need, we’ll use&npm install --save:现在,为了方便的移植我们需要的依赖项,我们将使用 npm install --save命令。npm&install&--save&express@4.10.2Now that express is installed we can create an&index.js&file that will setup our application.现在,express被安装,我们能够创建一个index.js文件来建立我们的应用。var&app&=&require('express')();
var&http&=&require('http').Server(app);
app.get('/',&function(req,&res){
&&res.send('&h1&Hello&world&/h1&');
http.listen(3000,&function(){
&&console.log('listening&on&*:3000');
});This translates into the following:Express initializes&app&to be a function handler that you can supply to an HTTP server (as seen in line 2).We define a route handler&/&that gets called when we hit our website home.We make the http server listen on port 3000.If you run&node index.js&you should see the following:以下是代码介绍:Express 初始化app 作为函数处理器,你能够提供给HTTP服务器&(第二行).我们定义一个路由处理器 / 用来访问我们站点的主页.我们让http服务器侦听3000端口.如果你运行&node index.js&你将看到如下:And if you point your browser to& 如果你通过你的浏览器访问Serving HTML提供HTMLSo far in&index.js&we’re calling&res.send&and pass it a HTML string. Our code would look very confusing if we just placed our entire application’s HTML there. Instead, we’re going to create a&index.html&file and serve it.Let’s refactor our route handler to use&sendFile&instead:到目前为止,在index.js 中,我们调用res.send,并且传递给它一个HTML字符串。如果我们仅仅将整个应用的HTML置于这里,我的代码将看上去令人沮丧。替代,我们将创建一个index.html文件,并且提供它。让我们用sendfile替代重构路由处理器。app.get('/',&function(req,&res){
&&res.sendFile(__dirname&+&'/index.html');
});And populate&index.html&with the following:并且用以下代码填入index.html:&!doctype&html&
&&&&&title&Socket.IO&chat&/title&
&&&&&style&
&&&&&&*&{&margin:&0;&padding:&0;&box-sizing:&border-&}
&&&&&&body&{&font:&13px&Helvetica,&A&}
&&&&&&form&{&background:�&padding:&3&position:&&bottom:&0;&width:&100%;&}
&&&&&&form&input&{&border:&0;&padding:&10&width:&90%;&margin-right:&.5%;&}
&&&&&&form&button&{&width:&9%;&background:&rgb(130,&224,&255);&border:&&padding:&10&}
&&&&&&#messages&{&list-style-type:&&margin:&0;&padding:&0;&}
&&&&&&#messages&li&{&padding:&5px&10&}
&&&&&&#messages&li:nth-child(odd)&{&background:&#&}
&&&&&/style&
&&&&&ul&id=&messages&&&/ul&
&&&&&form&action=&&&
&&&&&&&input&id=&m&&autocomplete=&off&&/&&button&Send&/button&
&&&&&/form&
&/html&If you restart the process (by hitting Control+C and running&node index&again) and refresh the page it should look like this:如果你重启进程( Control+C 并且再次&node index) 并且刷新页面,你将看到如下:Integrating Socket.IO集成Socket.IOSocket.IO is composed of two parts:A server that integrates with (or mounts on) the Node.JS HTTP Server:&socket.ioA client library that loads on the browser side:&socket.io-clientDuring development,&socket.io&serves the client automatically for us, as we’ll see, so for now we only have to install one module:Socket.IO 由两方面组成:一个服务器,集成了(或者挂载了)Node.JS HTTP Server:&socket.io浏览器端加载了客户端库:&socket.io-client随着发展,socket.io 自动为我们提供了客户端库。我们就会看到,我们仅仅只需下载一个模块:npm&install&--save&socket.ioThat will install the module and add the dependency to&package.json. Now let’s edit&index.js&to add it:那样将安装模块,并且在package.json添加dependency 。现在我们编辑index.js 来添加它。var&app&=&require('express')();
var&http&=&require('http').Server(app);
var&io&=&require('socket.io')(http);
app.get('/',&function(req,&res){
&&res.sendfile('index.html');
io.on('connection',&function(socket){
&&console.log('a&user&connected');
http.listen(3000,&function(){
&&console.log('listening&on&*:3000');
});Notice that I initialize a new instance of&socket.io&by passing the&http&(the HTTP server) object. Then I listen on theconnection&event for incoming sockets, and I log it to the console.Now in index.html I add the following snippet before the&&/body&:注意,我们通过传递http对象(HTTP服务器)初始化了一个新的socket.io实例. 然后,我们侦听到来的socket连接事件,并且记录它到控制台.现在我们在index.html的&body&标签前面添加如下代码段:&script&src=&/socket.io/socket.io.js&&&/script&
&&var&socket&=&io();
&/script&That’s all it takes to load the&socket.io-client, which exposes a&io&global, and then connect.Notice that I’m not specifying any URL when I call&io(), since it defaults to trying to connect to the host that serves the page.If you now reload the server and the website you should see the console print “a user connected”.Try opening several tabs, and you’ll see several messages:这样就加载了socket.io-client,暴露了一个io全局变量,并且连接。注意,我们当我们调用io(),没有指定任何URL,这样它默认尝试连接提供页面的主机。如果你现在重启服务器,并且网站你将看到控制台打印出“a user connected”.尝试打开多个网页标签,你将看到多条记录如下:Each socket also fires a special&disconnect&event:每个socket也会复发一个特别的disconnect事件:io.on('connection',&function(socket){
&&console.log('a&user&connected');
&&socket.on('disconnect',&function(){
&&&&console.log('user&disconnected');
});Then if you refresh a tab several times you can see it in action:如果你刷新页面,几秒钟后你能看到如下动作:Emitting eventsThe main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and&&is supported too.Let’s make it so that when the user types in a message, the server gets it as a&chat message&event. The&scripts section inindex.html&should now look as follows:触发事件在Socket.IO之前主要的想法是,你能够传递和接收任意你想要的事件,任意你想要的数据。任意对象能够转码为JSON,并且二进制数据也是支持的。让我们当用户键入消息,服务器作为chat message事件获取它。index.html中的脚本段落现在应该像如下样子:&script&src=&/socket.io/socket.io.js&&&/script&
&script&src=&/jquery-1.11.1.js&&&/script&
&&var&socket&=&io();
&&$('form').submit(function(){
&&&&socket.emit('chat&message',&$('#m').val());
&&&&$('#m').val('');
&&&&return&
&/script&And in&index.js&we print out the&chat message&event:并且在index.js中,我们打印出chatmessage事件:io.on('connection',&function(socket){
&&socket.on('chat&message',&function(msg){
&&&&console.log('message:&'&+&msg);
});The result should be like the following :结果应该像如下样子:Broadcasting广播The next goal is for us to emit the event from the server to the rest of the users.In order to send an event to everyone, Socket.IO gives us the&io.emit:下一步,我们从服务器发射事件到其他用户.为了能够发射一个事件给所有人, Socket.IO 给了我们&io.emit:io.emit('some&event',&{&for:&'everyone'&});If you want to send a message to everyone except for a certain socket, we have the&broadcast&flag:如果你想要发射一个消息给所有人,而非某一个socket,我们有broadcast&标志:io.on('connection',&function(socket){
&&socket.broadcast.emit('hi');
});In this case, for the sake of simplicity we’ll send the message to everyone, including the sender.在这个案例中,为了简单的目的,我们发送消息给所有人,包括发送者。io.on('connection',&function(socket){
&&socket.on('chat&message',&function(msg){
&&&&io.emit('chat&message',&msg);
});And on the client side when we capture a&chat message&event we’ll include it in the page. The total client-side JavaScript code now amounts to:在客户端,当我们捕获到一个chat message 事件,我们将渲染消息到我们的页面中。所有的客户端JavaScript 代码现在罗列如下:&script&
&&var&socket&=&io();
&&$('form').submit(function(){
&&&&socket.emit('chat&message',&$('#m').val());
&&&&$('#m').val('');
&&&&return&
&&socket.on('chat&message',&function(msg){
&&&&$('#messages').append($('&li&').text(msg));
&/script&And that completes our chat application, in about 20 lines of code! This is what it looks like:现在完成了我们的聊天应用。仅仅只需20行的代码!这个的样子如下:Getting this exampleYou can find it on GitHub&.$&git&clone&/guille/chat-example.gitsocket.io聊天室,做服务器集群会有问题吗? - CNode技术社区
这家伙很懒,什么个性签名都没有留下。
用express+socket.io做聊天室,用ngnix做负载均衡,后端有两台服务器,这样在广播消息的时候会有问题吗?
两个问题要注意
配置 nginx 支持 websocket
会话保持方面的坑。
,谢谢指点,如果nginx配置了websocket,会不会有这样的问题,比如:聊天在做socket连接的时候有人命中了服务器1,有人
命中了服务器2,这样在发送聊天广播信息的时候会不会有人收不到消息呢,只给连接到当前的服务器的用户发送?
你要想办法把消息共享这方面的逻辑移出 node 进程,放在一个共享的地方,比如接上 redis 之类的。
,好的,谢谢,有相关的资料吗?我参考参考。。
搜索「一致性散列」
pomelo 天生就是分布式集群的
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
服务器赞助商为
,存储赞助商为
,由提供应用性能服务。
新手搭建 Node.js 服务器,推荐使用无需备案的即时通讯之Socket.IO的学习 - 推酷
即时通讯之Socket.IO的学习
Web领域的实时推送技术,也被称作Realtime技术。这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新。它有着广泛的应用场景,比如在线聊天室、在线客服系统、评论系统、WebIM等。
谈到Web实时推送,就不得不说WebSocket。在WebSocket出现之前,很多网站为了实现实时推送技术,通常采用的方案是轮询(Polling)和Comet技术,Comet又可细分为两种实现方式,一种是长轮询机制,一种称为流技术,这两种方式实际上是对轮询技术的改进,这些方案带来很明显的缺点,需要由浏览器对服务器发出HTTP request,大量消耗服务器带宽和资源。面对这种状况,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并实现真正意义上的实时推送。
WebSocket协议本质上是一个基于TCP的协议,它由通信协议和编程API组成,WebSocket能够在浏览器和服务器之间建立双向连接,以基于事件的方式,赋予浏览器实时通信能力。既然是双向通信,就意味着服务器端和客户端可以同时发送并响应请求,而不再像HTTP的请求和响应。
为了建立一个WebSocket连接,客户端浏览器首先要向服务器发起一个HTTP请求,这个请求和通常的HTTP请求不同,包含了一些附加头信息,其中附加头信息”Upgrade: WebSocket”表明这是一个申请协议升级的HTTP请求,服务器端解析这些附加的头信息然后产生应答信息返回给客户端,客户端和服务器端的WebSocket连接就建立起来了,双方就可以通过这个连接通道自由的传递信息,并且这个连接会持续存在直到客户端或者服务器端的某一方主动的关闭连接。
前面讲到WebSocket是HTML5中新增的一种通信协议,这意味着一部分老版本浏览器(主要是IE10以下版本)并不具备这个功能,
,IE8目前仍以33%的市场份额占据榜首,好在chrome浏览器市场份额逐年上升,现在以超过26%的市场份额位居第二,同时微软前不久宣布停止对IE6的技术支持并提示用户更新到新版本浏览器,这个曾经让无数前端工程师为之头疼的浏览器有望退出历史舞台,再加上几乎所有的智能手机浏览器都支持HTML5,所以使得WebSocket的实战意义大增,但是无论如何,我们实际的项目中,仍然要考虑低版本浏览器的兼容方案:在支持WebSocket的浏览器中采用新技术,而在不支持WebSocket的浏览器里启用Comet来接收发送消息。
是一个完全由JavaScript实现、基于Node.js、支持WebSocket的协议用于实时通信、跨平台的开源框架,它包括了客户端的JavaScript和服务器端的Node.js。是一个为实时应用提供跨平台实时通信的库。socket.io 旨在使实时应用在每个浏览器和移动设备上成为可能,模糊不同的传输机制之间的差异。socket.io的名字源于它使用了浏览器支持并采用的HTML5 WebSocket 标准,因为并不是所有的浏览器都支持 WebSocket ,所以该库支持一系列降级功能:
Adobe& Flash& Socket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling
在大部分情境下,你都能通过这些功能选择与浏览器保持类似长连接的功能。
Socket.IO设计的目标是构建能够在不同浏览器和移动设备上良好运行的实时应用,如实时分析系统、二进制流数据处理应用、在线聊天室、在线客服系统、评论系统、WebIM等。Socket.IO已经具有众多强大功能的模块和扩展API,如(
(http session中间件,进行session相关操作)、
(cookie解析中间件)、
(以安全的方式传递Session)、
(JSON格式的记录日志工具)、
(可靠的消息队列)、
的适配器)、
(Redis的适配器)、
(服务端和客户端通讯的默认协议实现模块)等。
Socket.IO实现了实时、双向、基于事件的通讯机制,它解决了实时的通信问题,并统一了服务端与客户端的编程方式。启动了Socket以后,就像建立了一条客户端与服务端的管道,两边可以互通有无。它还能够和Express.js提供的传统请求方式很好的结合,即可以在同一个域名,同一个端口提供两种连接方式:request/response, websocket(flashsocket,ajax…).
参考资料:
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致2225人阅读
socket.io简介
在Html5中存在着这样的一个新特性,引入了websocket,关于websocket的内部实现原理可以看这篇文章,这篇文章讲述了websocket无到有,根据协议,分析数据帧的头,进行构建websocket。虽然代码短,但可以很好地体现websocket的原理。
,这个特性提供了浏览器端和服务器端的基于TCP连接的双向通道。但是并不是所有的浏览器都支持websocket特性,故为了磨平浏览器间的差异,为开发者提供统一的接口,引入了socket.io模块。在不支持websoket的浏览器中,socket.io可以降级为其他的通信方式,比如有AJAX
long polling ,JSONP Polling等。
新建一个package.json文件,在文件中写入如下内容:
"name": "socketiochatroom",
"version": "0.0.1",
"dependencies": {
"socket.io": "*",
"express":"*"
npm install
执行完这句,node将会从npm处下载socket.io和express模块。
服务器端的实现
在文件夹中添加index.js文件,并在文件中写入如下内容:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
"use strict";
res.end("&h1&socket server&/h1&")
var onLineUsers = {};
var onLineCounts = 0;
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('login', function (user) {
"use strict";
socket.name = user.userId;
if (!onLineUsers.hasOwnProperty(user.userId)) {
onLineUsers[user.userId] = user.userN
onLineCounts++;
io.emit('login', {onLineUsers: onLineUsers, onLineCounts: onLineCounts, user: user});
console.log(user.userName, "加入了聊天室");
socket.on('disconnect', function () {
"use strict";
if (onLineUsers.hasOwnProperty(socket.name)) {
var user = {userId: socket.name, userName: onLineUsers[socket.name]};
delete onLineUsers[socket.name];
onLineCounts--;
io.emit('logout', {onLineUsers: onLineUsers, onLineCounts: onLineCounts, user: user});
console.log(user.userName, "退出群聊");
socket.on('message', function (obj) {
"use strict";
io.emit('message', obj);
console.log(obj.userName, "说了:", obj.content);
http.listen(3000, function () {
"use strict";
console.log('listening 3000');
运行服务器端程序
node index.js
listening 3000
此时在浏览器中打开localhost:3000会得到这样的结果:
原因是在代码中只对路由进行了如下设置
app.get('/', function (req, res) {
"use strict";
res.end("&h1&socket server&/h1&")
服务器端主要是提供socketio服务,并没有设置路由。
客户端的实现
在客户端建立如下的目录和文件,其中json3.min.js可以从网上下载到。
- - - client.js
- - - index.html
- - - json3.min.js
- - - style.css
在index.html中
&!DOCTYPE html&
lang="en"&
charset="UTF-8"&
name="format-detection" content="telephone=no"/&
name="format-detection" content="email=no"/&
&1301群聊&
rel="stylesheet" type="text/css" href="./style.css"/&
src=":3000/socket.io/socket.io.js"&&
src="./json3.min.js"&&
id="loginbox"&
style="width: 260margin: 200"&
输入你在群聊中的昵称
type="text" style="width:180" placeholder="请输入用户名" id="userName" name="userName"/&
type="button" style="width: 50" value="提交" onclick="CHAT.userNameSubmit();"/&
id="chatbox" style="display:"&
style="background: #3d3d3d;height: 28width: 100%;font-size: 12px"&
style="line-height: 28color:#"&
style="text-align:margin-left: 10"&1301群聊&
style="float:margin-right: 10px"& id="showUserName"&&|
href="javascript:;" onclick="CHAT.logout()" style="color: #"&退出&&
id="chat"&
id="message" class="message"&
id="onLineCounts"
style="background: #EFEFF4; font-size: 12margin-top: 10margin-left: 10color: #666;"&
class="input-box"&
class="input"&
type="text" maxlength="140" placeholder="输入聊天内容 " id="content" name="content" &
class="action"&
type="button" id="mjr_send" onclick="CHAT.submit();"&提交&
type="text/javascript" src="./client.js"&&
在client.js中
(function () {
"use strict";
var d = document,
w = window,
dd = d.documentElement,
db = d.body,
dc = d.compatMode === "CSS1Compat",
dx = dc ? dd : db,
ec = encodeURIComponent,
p = parseInt;
w.CHAT = {
msgObj: d.getElementById("message"),
screenHeight: w.innerHeight ? w.innerHeight : dx.innerHeight,
userName: null,
userId: null,
socket: null,
scrollToBottom: function () {
w.scrollTo(0, this.msgObj.clientHeight);
logout: function () {
w.top.location.reload();
submit: function () {
var content = d.getElementById('content').
if (content != '') {
var obj = {
userId: this.userId,
userName: this.userName,
content: content
this.socket.emit('message', obj);
d.getElementById('content').value = '';
return false;
genUid: function () {
return new Date().getTime() + "" + Math.floor(Math.random() * 889 + 100);
updateSysMsg: function (o, action) {
var onLineUsers = o.onLineU
var onLineCounts = o.onLineC
var user = o.
var userHtml = '';
var separator = '';
for (var key in onLineUsers) {
if (onLineUsers.hasOwnProperty(key)) {
userHtml += separator + onLineUsers[key];
separator = '、';
d.getElementById('onLineCounts').innerHTML = '当前共有' + onLineCounts + "在线列表: " + userH
var html = '';
html += '&div class="msg_system"&';
html += user.userN
html += (action === "login") ? "加入了群聊" : "退出了群聊";
html += '&/div&';
var section = d.createElement('section');
section.className = 'system J-mjrlinkWrap J-cutMsg';
section.innerHTML =
this.msgObj.appendChild(section);
this.scrollToBottom();
userNameSubmit: function () {
var userName = d.getElementById('userName').
if (userName != '') {
d.getElementById('userName').value = '';
d.getElementById('loginbox').style.display = 'none';
d.getElementById('chatbox').style.display = 'block';
this.init(userName);
return false;
init: function (userName) {
this.userId = this.genUid();
this.userName = userN
d.getElementById('showUserName').innerHTML = this.userN
this.scrollToBottom();
this.socket = io.connect('192.168.3.155:3000');
this.socket.emit('login', {userId: this.userId, userName: this.userName});
this.socket.on('login', function (o) {
CHAT.updateSysMsg(o, 'login');
this.socket.on('logout', function (o) {
CHAT.updateSysMsg(o, 'logout');
this.socket.on("message", function (obj) {
var isMe = (obj.userId === CHAT.userId);
var contentDiv = '&div&' + obj.content + '&/div&';
var userNameDiv = '&span&' + obj.userName + '&/span&';
var section = d.createElement('section');
if (isMe) {
section.className = 'user';
section.innerHTML = contentDiv + userNameD
section.className = 'service';
section.innerHTML = userNameDiv + contentD
CHAT.msgObj.appendChild(section);
CHAT.scrollToBottom();
d.getElementById('userName').onkeydown = function (e) {
console.log(e);
if (e.keyCode === 13) {
CHAT.userNameSubmit();
d.getElementById('content').onkeydown = function (e) {
if (e.keyCode === 13) {
CHAT.submit();
服务器端已经运行,现将客户端也运行起来得到下图:
添加了new和pidian两个用户,并发送信息和进行退出,得到下面的结果:
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:49622次
排名:千里之外
原创:45篇
(4)(7)(9)(2)(6)(1)(4)(6)(2)(3)(4)(1)

我要回帖

更多关于 socket.io 一对一聊天 的文章

 

随机推荐