Node.js+socket.io简单在线聊天

来源:互联网 发布:金融 大数据 微线索 编辑:程序博客网 时间:2024/05/22 05:29

Node.js:0.10.31
在e:/nodejs/新建文件夹easychat
在easychat/下新建app.js 和 index.html

app.js:

var fs = require('fs')    , http = require('http')    , socketio = require('socket.io');  var server = http.createServer(function(req, res) {    res.writeHead(200, { 'Content-type': 'text/html'});    res.end(fs.readFileSync(__dirname + '/index.html'));}).listen(3000, function() {    console.log('Listening at: http://localhost:3000');});  socketio.listen(server).on('connection', function (socket) {    socket.on('message', function (msg) {        console.log('Message Received: ', msg);        socket.broadcast.emit('message', msg);    });});
index.html:

<html><head>    <script src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script>    <script src="/socket.io/socket.io.js"></script>    <script>        $(function(){            var iosocket = io.connect();              iosocket.on('connect', function () {                $('#incomingChatMessages').append($('<li>You have Connected</li>'));                  iosocket.on('message', function(message) {                    $('#incomingChatMessages').append($('<li></li>').text(message));                });                iosocket.on('disconnect', function() {                    $('#incomingChatMessages').append('<li>Disconnected</li>');                });            });              $('#outgoingChatMessage').keypress(function(event) {                if(event.which == 13) {                    event.preventDefault();                    iosocket.send($('#outgoingChatMessage').val());                    $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));                    $('#outgoingChatMessage').val('');                }            });        });    </script></head><body>Incoming Chat: <ul id="incomingChatMessages"></ul><br /><input type="text" id="outgoingChatMessage"></body></html>
安装socket.io

npm install socket.io

这样就可以打开两个浏览器进行聊天了,局域网内访问http://ip:3000也可以实现聊天




0 0
原创粉丝点击