使用nodejs引用socket.io做聊天室

Server:

 

var app = require('http').createServer(handler)

  , io = require('socket.io').listen(app)

  , fs = require('fs');



app.listen(80);

console.log('server listen on port 80');



function handler (req, res) {

  fs.readFile(__dirname + '/public/index.html',

  function (err, data) {

    if (err) {

      res.writeHead(500);

      return res.end('Error loading index.html');

    }



    res.writeHead(200);

    res.end(data);

  });

}



var chatroom=io.of('/chat').on('connection',function(socket){

    console.log(id+'connected');

    var id=null;

    socket.on('setid',function(sid){

        id=sid;

        socket.emit('id',id);

        chatroom.emit('msg',id+' join the chatroom');

    });

    socket.on('msg',function(msg){

        chatroom.emit('msg',id+' : '+msg);

    });

})

Client:

<!doctype html>

<html>

<head>

    <title>socket.io</title>

    <script type="text/javascript" src="/socket.io/socket.io.js"></script>

    <style type="text/css">

    body{

        font: message-box;

    }

    #output{

        height:200px;

        border:1px solid #888;

        overflow-y: scroll;

    }

    </style>

</head>

<body>

    <div id="output"></div>

    <span id="userid"></span>

    <input type="text" id="text" placeholder='input your name'>

    <button id="btn">connect</button>

    

    <script type="text/javascript">

        var socket = null;

        var btn=document.getElementById('btn');

        var text=document.getElementById('text');

        var output=document.getElementById('output');

        btn.onclick=function(e){

            console.log('btn click');

            socket = io.connect('http://localhost/chat');

            socket.on('connect',function(){

                console.log('connect');

                socket.emit('setid',text.value);

                socket.on('id',function(id){

                    document.getElementById('userid').innerText=id+':';

                });

                socket.on('msg',function(msg){

                    output.innerText+=(msg+'\n');

                    output.scrollTop=output.scrollHeight;

                });

                btn.innerText='send';

                text.placeholder='input msg';

                text.value='';

                btn.onclick=function(e){

                    socket.emit('msg',text.value);

                    text.value='';

                }

            });

        };

    </script>

</body>

</html>

 

你可能感兴趣的:(socket)