Nodejs webSocket + socket.io 简易聊天室
Nodejs webSocket + socket.io 简易聊天室
-
安装socket.io:npm install socket.io -g
-
服务端代码:server.js
var app = require(‘http’).createServer(handler); var io = require(‘socket.io’).listen(app); var fs = require(‘fs’);
app.listen(8080);
function handler(req, res) { fs.readFile(__dirname + ‘/index.html’, function(err, data) { if (err) { res.writeHead(500); return res.end(‘Error loading index.html’); }
res.writeHead(200); res.end(data); }); }
io.sockets.on(‘connection’, function(socket) { socket.broadcast.emit(‘notify’, { message : ‘欢迎“’ + socket.id + “”进入了聊天室” });
socket.on(‘sendMessage’, function(data) { data.nickname = socket.store.data.nickname; socket.broadcast.emit(‘newMessage’, data); // 给公众发消息 socket.emit(‘newMessage’, data); // 给自己发消息 });
socket.on(‘setNickname’, function(data){ var _nickname = socket.store.data.nickname; socket.set(‘nickname’, data.nickname, function(){ socket.broadcast.emit(‘notify’, { message : ‘“’ + _nickname + ‘”’ + ‘更名为:“’ + data.nickname + ‘”’ }); }); });
socket.on(‘disconnect’, function(){ socket.broadcast.emit(‘notify’, { message : ‘“’ + socket.store.data.nickname + “”离开了聊天室” }); }); });
- 客户端代码:index.html
<!doctype html> <html> <head> <title>Socket.io Test</title> <script type=“text/javascript” src="/socket.io/socket.io.js"></script> <script type=“text/javascript” src=“https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js”></script> <style type=“text/css”>
- { font-family:“微软雅黑” “黑体”; font-size:14px; } #notify { color:red; font-style:italic; } input { padding:3px; } </style> </head> <body> <script> Date.prototype.datetime = function() { year = this.getFullYear(); month = this.getMonth() + 1; day = this.getDate(); hours = this.getHours(); minute = this.getMinutes(); second = this.getSeconds();
month = month > 10 ? month : ‘0’ + month; day = day > 10 ? day : ‘0’ + day; hours = hours > 10 ? hours : ‘0’ + hours; minute = minute > 10 ? minute : ‘0’ + minute; second = second > 10 ? second : ‘0’ + second;
return year+’-’+month+’-’+day+’ ‘+hours+’:’+minute+’:’+second; };
$(document).ready(function(){ var socket = io.connect(‘http://localhost:8080’);
/**
- 播报消息列表里的消息 */ var notifies = new Array(); var notifyLoop = setInterval(function() { if(notifies.length > 0) { $(’#notify’).text(notifies.splice(0, 1)[0]); if($(’#notify’).is(’:hidden’)) { $(’#notify’).slideDown(400); } } else { $(’#notify’).slideUp(400); } }, 2000);
/**
- 初次连接显示公告 */ socket.on(‘notify’, function (data) { notifies.push("["+ (new Date).datetime() + “]”+ data.message); });
/**
- 接受消息 */ socket.on(‘newMessage’, function(data){ $(’#publicMsg’).append("<div style=“color:#C4C4C4; margin-top:10px;”>"+data.nickname+" “+(new Date).datetime()+ “</div><div>”+ data.message+”</div>"); });
/**
- 发送消息 */ $(’#sendMessage’).click(function(){ messageText = $(’#messageText’).val(); if(messageText != ‘’) { $(’#messageText’).val(null); socket.emit(‘sendMessage’, { message: messageText }); } });
$(’#nickname’).change(function(){ nickname = $(this).val(); if(nickname != ‘’) { socket.emit(‘setNickname’, { ‘nickname’: nickname }); } }); }); </script> <div id=“notify” style=“display:none;”> </div> <div id=“publicMsg”></div> <div id=“privateMsg”></div> <input type=“text” id=“nickname” value="" style=“width:50px;” /><input type=“text” id=“messageText” style=“width:300px;” /> <input type=“button” id=“sendMessage” value=“Send” /> </body> </html>
-
启动服务器: node server.js
-
打开浏览器:http://127.0.0.1:8080/
Node.js WebSocket + Socket.IO 简易聊天室
1. 安装 Socket.IO
首先需要安装 socket.io
模块。可以使用以下命令全局安装:
npm install socket.io -g
2. 服务端代码:server.js
服务端主要负责处理 HTTP 请求以及 WebSocket 连接。
// server.js
var http = require('http');
var fs = require('fs');
var socketIo = require('socket.io');
var app = http.createServer(handler);
var io = socketIo.listen(app);
app.listen(8080);
function handler(req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function(socket) {
socket.broadcast.emit('notify', {
message: '欢迎 "' + socket.id + '" 进入了聊天室'
});
socket.on('sendMessage', function(data) {
data.nickname = socket.request.session.username || socket.id;
socket.broadcast.emit('newMessage', data); // 广播给其他用户
socket.emit('newMessage', data); // 发送给自身
});
socket.on('setNickname', function(data) {
var _nickname = socket.request.session.username;
socket.request.session.username = data.nickname;
socket.broadcast.emit('notify', {
message: '"' + _nickname + '" 更名为:"' + data.nickname + '"'
});
});
socket.on('disconnect', function() {
socket.broadcast.emit('notify', {
message: '"' + socket.request.session.username + '" 离开了聊天室'
});
});
});
3. 客户端代码:index.html
客户端代码用于展示聊天界面并处理用户的输入。
<!DOCTYPE html>
<html>
<head>
<title>Socket.io Test</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style>
* { font-family:"微软雅黑", "黑体"; font-size:14px; }
#notify { color:red; font-style:italic; }
input { padding:3px; }
</style>
</head>
<body>
<script>
Date.prototype.datetime = function() {
var year = this.getFullYear();
var month = this.getMonth() + 1;
var day = this.getDate();
var hours = this.getHours();
var minute = this.getMinutes();
var second = this.getSeconds();
month = month > 10 ? month : '0' + month;
day = day > 10 ? day : '0' + day;
hours = hours > 10 ? hours : '0' + hours;
minute = minute > 10 ? minute : '0' + minute;
second = second > 10 ? second : '0' + second;
return year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':' + second;
};
$(document).ready(function() {
var socket = io.connect('http://localhost:8080');
/**
* 播报消息列表里的消息
*/
var notifies = [];
var notifyLoop = setInterval(function() {
if (notifies.length > 0) {
$('#notify').text(notifies.splice(0, 1)[0]);
if ($('#notify').is(':hidden')) {
$('#notify').slideDown(400);
}
} else {
$('#notify').slideUp(400);
}
}, 2000);
/**
* 初次连接显示公告
*/
socket.on('notify', function(data) {
notifies.push("[" + (new Date).datetime() + "] " + data.message);
});
/**
* 接受消息
*/
socket.on('newMessage', function(data) {
$('#publicMsg').append(
"<div style='color:#C4C4C4; margin-top:10px;'>" +
data.nickname + " " + (new Date).datetime() +
"</div><div>" + data.message + "</div>"
);
});
/**
* 发送消息
*/
$('#sendMessage').click(function() {
var messageText = $('#messageText').val();
if (messageText !== '') {
$('#messageText').val('');
socket.emit('sendMessage', { message: messageText });
}
});
$('#nickname').change(function() {
var nickname = $(this).val();
if (nickname !== '') {
socket.emit('setNickname', { nickname: nickname });
}
});
});
</script>
<div id="notify" style="display:none;"></div>
<div id="publicMsg"></div>
<input type="text" id="nickname" value="" style="width:50px;" />
<input type="text" id="messageText" style="width:300px;" />
<input type="button" id="sendMessage" value="Send" />
</body>
</html>
4. 启动服务器
在命令行中运行以下命令启动服务器:
node server.js
5. 打开浏览器
打开浏览器访问 http://127.0.0.1:8080/
即可看到简易的聊天室页面。
Markdown 标记啊楼主…
好文
Nodejs WebSocket + Socket.io 简易聊天室
本示例展示了如何使用 socket.io
和 Node.js
创建一个简易的聊天室。我们将通过一个服务端 (server.js
) 和客户端 (index.html
) 来实现基本的通信功能。
安装socket.io
npm install socket.io --save
服务端代码 (server.js
)
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8080);
function handler(req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function(socket) {
socket.broadcast.emit('notify', {
message: '欢迎 "' + socket.id + '" 进入了聊天室'
});
socket.on('sendMessage', function(data) {
data.nickname = socket.request.session.nickname;
socket.broadcast.emit('newMessage', data); // 发送给其他人
socket.emit('newMessage', data); // 发送给自身
});
socket.on('setNickname', function(data) {
var oldNickname = socket.request.session.nickname;
socket.request.session.nickname = data.nickname;
socket.set('nickname', data.nickname, function() {
socket.broadcast.emit('notify', {
message: oldNickname + ' 更名为:' + data.nickname
});
});
});
socket.on('disconnect', function() {
socket.broadcast.emit('notify', {
message: socket.request.session.nickname + ' 离开了聊天室'
});
});
});
客户端代码 (index.html
)
<!DOCTYPE html>
<html>
<head>
<title>Socket.io Test</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style>
* { font-family:"微软雅黑"; font-size:14px; }
#notify { color:red; font-style:italic; }
input { padding:3px; }
</style>
</head>
<body>
<script>
Date.prototype.datetime = function() {
var year = this.getFullYear();
var month = this.getMonth() + 1;
var day = this.getDate();
var hours = this.getHours();
var minute = this.getMinutes();
var second = this.getSeconds();
month = month > 10 ? month : '0' + month;
day = day > 10 ? day : '0' + day;
hours = hours > 10 ? hours : '0' + hours;
minute = minute > 10 ? minute : '0' + minute;
second = second > 10 ? second : '0' + second;
return year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':' + second;
};
$(document).ready(function() {
var socket = io.connect('http://localhost:8080');
var notifies = [];
var notifyLoop = setInterval(function() {
if (notifies.length > 0) {
$('#notify').text(notifies.splice(0, 1)[0]);
if ($('#notify').is(':hidden')) {
$('#notify').slideDown(400);
}
} else {
$('#notify').slideUp(400);
}
}, 2000);
socket.on('notify', function(data) {
notifies.push('[' + (new Date()).datetime() + '] ' + data.message);
});
socket.on('newMessage', function(data) {
$('#publicMsg').append(
'<div style="color:#C4C4C4; margin-top:10px;">' + data.nickname + ' ' + (new Date()).datetime() + '</div>' +
'<div>' + data.message + '</div>'
);
});
$('#sendMessage').click(function() {
var messageText = $('#messageText').val();
if (messageText != '') {
$('#messageText').val('');
socket.emit('sendMessage', { message: messageText });
}
});
$('#nickname').change(function() {
var nickname = $(this).val();
if (nickname != '') {
socket.emit('setNickname', { nickname: nickname });
}
});
});
</script>
<div id="notify" style="display:none;"></div>
<div id="publicMsg"></div>
<input type="text" id="nickname" value="" style="width:50px;" />
<input type="text" id="messageText" style="width:300px;" />
<input type="button" id="sendMessage" value="Send" />
</body>
</html>
启动服务器
node server.js
打开浏览器
http://127.0.0.1:8080/
以上代码展示了如何使用 socket.io
实现一个简单的聊天室,包括用户连接、断开连接、设置昵称以及发送消息等功能。