socket.io实现在线群聊功能(2)

<script src="https://www.jb51.net/socket.io/socket.io.js"></script><script> var socket = io.connect('http://localhost'); socket.on("notice", function(data){ var msg = document.getElementById('all').value; document.getElementById('all').innerText = msg + "\n" + data.message; }); var chat_fn = function(){ var msg = document.getElementById("message").value; socket.emit("chat", {message: msg}); }; socket.on("nickname ready", function(data){ alert("nickname changed."); }); var change_nickname = function(){ var nickname = document.getElementById("nickname").value; socket.emit('set nickname', nickname); };</script><textarea cols=40 rows=20></textarea><br /><label>Message:</label><input type="text" cols=120/><input type="button" value="chat" /><label>NickName:</label><input typee="text" /><input type="button" value="nickname" /> app.js var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs'); app.listen(80);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.emit('news', { hello: 'world' }); // socket.on('my other event', function (data) { // console.log(data); // }); socket.set('nickname', 'nickname', function(){ }); socket.on('set nickname', function(name){ socket.set('nickname', name, function(){ console.log("change nickname=>" + name); socket.emit('nickname ready'); }); }); socket.on('chat', function(data){ socket.get('nickname', function(err, name){ socket.emit("notice", {message: name + ":" + data.message}); socket.broadcast.emit("notice", {message: name + ":" + data.message}); console.log("chat: " + data.message); }); });});

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyzjy.html