在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → HTML5 socket在线聊天程序 源码

HTML5 socket在线聊天程序 源码

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.06M
  • 下载次数:45
  • 浏览次数:592
  • 发布时间:2014-09-13
  • 实例类别:C#语言基础
  • 发 布 人:TESTtrtret
  • 文件格式:.zip
  • 所需积分:2
 相关标签: HTML5 聊天 HTML 在线

实例介绍

【实例简介】
【实例截图】

【核心代码】


var http = require('http'),
url = require("url"),
path = require("path"),
fs = require('fs'),
zlib = require("zlib"),
io = require('socket.io'),
mime = require("./mime").types,
config = require("./config"),
log = require("./log").Log,
tools = require("./serverTools").Tools,
defaultPort = 8080, port = defaultPort;

// 获取参数
process.argv.forEach(function (val, index, array) {
	var p = val.split("=");
	if (p.length > 1 && p[0] == "port") {
		port = p[1];
	} else if (p.length > 1 && p[0] == "log") {
		var logType = p[1];
		for (var i=0, l=log.levelList.length; i<l; i  ) {
			if (log.levelList[i] === logType) {
				log.level = i;
				break;
			}
		}
	}
});

//获取默认路径
var modulePaths = module.paths, serverPath = "/", webPath = "";
if (modulePaths.length > 0) {
	serverPath = path.dirname(modulePaths[0]);
}
webPath = serverPath   "/web";
log.serverPath = serverPath;

var server = http.createServer(function (request, response) {

	var clientIp = request.connection.remoteAddress;
	
	//查找文件路径
    var pathname = url.parse(request.url).pathname;
	if (pathname.lastIndexOf("/") == pathname.length - 1) {
		pathname  = config.DefaultPage;
	}
    var realPath = webPath   pathname.replace(/\.\./g, "");
	
	var ext = path.extname(realPath);

	ext = ext ? ext.slice(1) : 'unknown';
	//根据类型设置过期时间
	if (ext.match(config.Expires.fileMatch)) {
	    var expires = new Date();
		expires.setTime(expires.getTime()   config.Expires.maxAge * 1000);
		response.setHeader("Expires", expires.toUTCString());
		response.setHeader("Cache-Control", "max-age="   config.Expires.maxAge);

	}
	var contentType = mime[ext] || "text/plain";
	response.setHeader("Content-Type", contentType);

	log.info(clientIp   " access url : "   request.url);

	//判断文件是否存在
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL "   pathname   " was not found on this server.");
			log.error(realPath   " is not exists!");
            response.end();
        } else {

			/*
			if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
				response.writeHead(304, "Not Modified");
				response.end();
			}*/

            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });

                    response.end("realPath = "  realPath  ", errno:"   err.errno   ", errcode:"   err.code );
                } else {

					//使用 gzip 压缩
					var raw = fs.createReadStream(realPath);
					var acceptEncoding = request.headers['accept-encoding'] || "";
					var matched = ext.match(config.Compress.match);
					if (matched && acceptEncoding.match(/\bgzip\b/)) {
						response.writeHead(200, "Ok", {
							'Content-Encoding': 'gzip'
						});
						raw.pipe(zlib.createGzip()).pipe(response);
					} else if (matched && acceptEncoding.match(/\bdeflate\b/)) {
						response.writeHead(200, "Ok", {
							'Content-Encoding': 'deflate'
						});
						raw.pipe(zlib.createDeflate()).pipe(response);
					} else {
						response.writeHead(200, "Ok");
						raw.pipe(response);
					}

                    //response.write(file, "binary");
                    //response.end();
                }
            });
        }
    });
});

server.listen(port);
log.info("http server is started. port : "   port);
log.info("web path : "   webPath);


//创建socket
var socketSetting = {
	//关闭 socket.io 的debug 信息
	"log level" : log.level
},
socket = io.listen(server, socketSetting), userList = {};

//添加连接监听
socket.on('connection', function(client){
	var clientIp = client.handshake.address.address, userName = tools.checkWhiteList(clientIp); 
	if (!userName) {
		return;
	}

	if (!userList[userName]) {
		userList[userName] = 1;
	} else {
		userList[userName]   ;
	}
	
	/*
	//连接成功则执行下面的监听
	client.on('message',function(event){ 
		console.log('Received message from client!',event);
	});
	*/
	
	//断开连接callback
	client.on('disconnect',function(){
		if (userList[userName]) {
			userList[userName] --;
			if (userList[userName] == 0) {
				delete userList[userName];
			}
		}
		log.info("client("   userName   ") ["   clientIp   "] has disconnected");
		client.broadcast.emit('userDisConnected', {user: (userList[userName] > 0 ? userName   " 的马甲": userName), userList: userList});
	});
	
	//发送消息给客户端	
	client.emit('open', {userList: userList});
		
	client.on('sendMsg', function (data) {
		client.broadcast.emit('msg', { user: userName, msg: data.msg, msgType: data.msgType, userList: userList });
		log.debug("client("   userName   ") ["   clientIp   "] send msg:\n"   data.msg);
	});
	//广播信息给除当前用户之外的用户
	client.broadcast.emit('userConnected', {user: (userList[userName] > 1 ? userName   " 的马甲": userName), userList: userList});
	//广播给全体客户端
	//io.sockets.emit('all users');
});


标签: HTML5 聊天 HTML 在线

实例下载地址

HTML5 socket在线聊天程序 源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警