webSocket + socket.io 简易聊天室
发布于 1年前 作者 leeson 2313 次浏览
  1. 安装socket.io:npm install socket.io -g

  2. 服务端代码: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 + “”离开了聊天室” }); }); });


  1. 客户端代码: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()+ "
“+ data.message+”
"); });

/**

  • 发送消息 */ $(‘#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>
<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> --------------------------------------------------
  1. 启动服务器: node server.js

  2. 打开浏览器:http://127.0.0.1:8080/

2 回复

Markdown 标记啊楼主…

回到顶部