【即时通讯】 前端开发Nodejs+Socket.io实现实时聊天

移动web前端开发 c|前端开发 高级教程|前端开发实战教程视频

app.js
javascript 代码

var app = require(‘http’).createServer(handler),
    io = require(‘socket.io’).listen(app),
    fs = require(‘fs’)
app.listen(3000)
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.nickname = null
    socket.on(‘set nickname’, function(name) {
        socket.nickname = name
        console.log(‘change nickname=>’ + name)
        socket.emit(‘nickname ready’)
    })
    socket.on(‘chat’, function(data) {
        console.log(socket.nickname)
        console.log(data.message)
        socket.emit(‘notice’, { message: socket.nickname + ‘:’ + data.message })
        console.log(‘chat: ‘ + data.message)
    })
})

注意:其中用到socket.io存储数据的方法,socket.nickname相当于在socket中存储了nickname的数据,在服务端和浏览器端共享。我在这里踩过坑,现在的socket.io中设置变量的值,不再使用socket.set()/socket.get()
并且这里值得注意的地方:
javascript 代码

socket.emit(‘notice’,{‘message’:socket.nickname+’:’+data.message});

这种存储数据的结构,我原来一直想使用socket.nickname:data.message,总是会出错

index.html
html 代码

<textarea id=”all” cols=40 rows=20></textarea>
<label>Message:</label>
<input id=”message” type=”text” name=”message” cols=120/>
<input id=”chat_btn” type=”button” value=”chat” onclick=”javascript:chat_fn()” />
<label>NickName:</label>
<input id=”nickname” typee=”text” name=”nickname” />
<input id=”chang_name” type=”button” value=”nickname” onclick=”javascript:change_nickname()” />

javascript 代码

<script src=”/socket.io/socket.io.js”></script>
<script type=”text/javascript”>
    var socket = io.connect(“https://www.rokub.com:3000”);
    socket.on(‘notice’, function (data) {
        var msg = document.getElementById(‘all’).value;
        alert(data.message);
        document.getElementById(‘all’).innerHTML = msg + ‘\n’ + data.message;
    });
    var chat_fn = function () {
        var msg = document.getElementById(“message”).value;
        socket.emit(‘chat’, { message: msg });
        console.log(‘send a message’);
    };
    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>

html5与前端开发视频教程|招聘 web前端开发|web前端技术开发期末考试题

» 本文来自:前端开发者 » 《【即时通讯】 前端开发Nodejs+Socket.io实现实时聊天》
» 本文链接地址:https://www.rokub.com/4608.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!