基于websocket,使用node.js 做一个聊天室

来源:互联网 发布:淘宝供销平台新玩法 编辑:程序博客网 时间:2024/06/06 13:14

1.首先安装node.js   node.js的管理包npm

2.npm在大天朝需要换一个源 

参考http://blog.csdn.net/liulangdeshusheng/article/details/45690123

3.安装socket.io   命令:   npm install socket.io

4.创建一个app.js   

代码如下:

var fs = require('fs')//文件操作    , http = require('http')//http服务器    , socketio = require('socket.io');//socket.io,用来和前台进行交互  var server = http.createServer(function(req, res) {    res.writeHead(200, { 'Content-type': 'text/html'});    //将index.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('接受到 ', msg);        //将信息发送给其他客户端        socket.broadcast.emit('message', msg);    });});

创建index.html

<html><head><meta charset="utf-8">    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>    <script src="/socket.io/socket.io.js"></script>    <script>        $(function(){            var iosocket = io.connect();              iosocket.on('connect', function () {                $('#incomingChatMessages').append($('<li>已连接!</li>'));                  iosocket.on('message', function(message) {                    $('#incomingChatMessages').append($('<li></li>').text(message));                });                iosocket.on('disconnect', function() {                    $('#incomingChatMessages').append('<li>失去连接</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>控制台:&nbsp;<ul id="incomingChatMessages"></ul><br /><input type="text" id="outgoingChatMessage"></body></html>


0 0