H5+MUI+Node.js+Socket.io实现即时聊天以及发送+图片压缩+图片预览保存



	
		
		
		
		
		
		//发送图片后,点击图片大图预览用的
		
			
		 
		
		
	

	
		


		
		
!
手指上滑,取消发送
//创建数据库的一些操作 //登录成功后记录的一些个人信息 //服务端

服务端接收图片,并返回网络路径:

int l = Request.Files["uploadkey"].ContentLength;
byte[] buffer = new byte[l];
Stream s = Request.Files["uploadkey"].InputStream;
//string imgtype = Request.Files[3 + i].ContentType;
//image/png
System.Drawing.Bitmap image = new System.Drawing.Bitmap(s);
string imgname = Common.GetGuid() + ".jpg";
string path = "Images/" + DateTime.Now.ToString("yyyyMMdd");
if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
{
    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
}
string newurl=Server.MapPath(path + "/" + imgname);
image.Save(newurl);

db.js源码:

/*管理本地sql相关脚本*/

var DBConn = function() {

	var dbName = 'abcde'; //数据库名
	var version = '2.0'; //版本信息
	var description = 'abcd'; //描述
	var maxSize = 5 * 1024 * 1024; //最大值
	var dbObj = null;

	//打开数据库
	function openDB() {
		try {
			if (!dbObj) {
				dbObj = openDatabase(dbName, version, description, maxSize);
			}
		} catch (e) {
			console.log("打开数据库出现未知错误: " + e);
			dbObj = null;
		}
		return dbObj;
	}

	this.getDBconn = function() {
		openDB();
		return dbObj;
	}

	this.executeSqlDefault = function(sqlStr, params, successHandler, errorHandler) {
		openDB();
		dbObj.transaction(function(tx) {
			tx.executeSql(sqlStr, params, successHandler, errorHandler);
		}, function(transaction, result) {}, function(tx, error) {});
	}

	this.executeSqlTrans = function(fun, successHandler, errorHandler) {
		openDB();
		dbObj.transaction(fun, errorHandler, successHandler);
	}

	//修改数据库版本信息
	this.changeDBVersion = function(oldVersion, newVersion) {
		dbObj = openDB();
		dbObj.changeVersion(oldVersion, newVersion, function(transaction, result) {}, function(tx, error) {});
	}

	//创建表
	this.createTable = function(tableName, sql) {
		dbObj = openDB();
		isExitTable(tableName,
			function() {
				//存在表,不执行
			},
			function() {
				//不存在,执行创建
				dbObj.transaction(function(tx) {
					tx.executeSql(sql, [], function(transaction, result) {
						console.log("表[" + tableName + "]创建失败");
					}, function(tx, error) {});
				});
			}
		);
	}

	//不判断直接执行创建表
	this.createTableNoCheck = function(tableName, sql) {
		dbObj = openDB();
		
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [], function(transaction, result) {
				//mui.toast("表["+tableName+"]创建失败"); 
			}, function(tx, error) {

			});
		});
	}

	//判断某表是否存在:表名、存在回调函数、不存在回调函数
	this.isExitTable = function(tableName, exitFun, noexitFun) {
		dbObj = openDB();
		var sql = "select * from sqlite_master where type='table' and name = ?";
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [tableName], function(transaction, result) {
				if (result.rows.length > 0 && exitFun) {
					exitFun.call();
				} else if (result.rows.length <= 0 && noexitFun) {
					noexitFun.call();
				}
			}, function(tx, error) {

			});
		});

	}

	//删除表数据:表名,删除成功回调函数
	this.delTbleData = function(tableName, callBackFun) {
		dbObj = openDB();
		var sql = "delete from ?";
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [tableName], callBackFun, function(tx, error) {});
		});
	}

	//删除表,删除成功回调函数
	this.delTbleData = function(tableName, callBackFun) {
		dbObj = openDB();
		var sql = "drop table ?";
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [tableName], callBackFun, function(tx, error) {});
		});
	}
	this.delTble = function(tableName, callBackFun,callErrFun) {
		dbObj = openDB();
		var sql = "drop table "+tableName;
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [], callBackFun, callErrFun);
		});
	}
	this.executeScarl = function(sql, callBackFun, callErrFun) {
		dbObj = openDB();
		dbObj.transaction(function(tx) {
			tx.executeSql(sql, [], callBackFun, callErrFun);
		});
	}

	//登录时初始化数据库表
	this.initTable = function() {
		var sql = "";
		//最近联系人表

		sql = "CREATE TABLE if not exists chart_list (id UNIQUE,send,receive,addtime,content,contentType,groupid,uname,gname,pic)";
		this.createTableNoCheck('chart_list', sql);
		//最近联系人聊天内容表
		sql = "CREATE TABLE if not exists chart_list_content (id UNIQUE,send,receive,addtime,content,contentType,type,isread,upic)";
		this.createTableNoCheck('chart_list_content', sql);
		//群组聊天纪录表

		sql = "CREATE TABLE if not exists chart_group_list_content (id UNIQUE,send,content,contentType,addtime,type,groupid,uname,upic)";
		this.createTableNoCheck('chart_group_list_content', sql);



		sql = "create table if not exists dynamic (id,userid,realname,userimg,title,contents,joindate)";
		this.createTableNoCheck('dynamic', sql);
		

		sql = "create table if not exists dynamic_zan (id,did,username,joindate)";
		this.createTableNoCheck('dynamic_zan', sql);
		
		sql = "create table if not exists dynamic_comment (id,did,username,comment,joindate)";
		this.createTableNoCheck('dynamic_comment', sql);

		plus.storage.setItem("isdb", "true");
	}
}

login.js源码

//一些全局变量
var server = "http://192.168.1.106:8003/System/Controls/appinterface.aspx";

(function($, window) {

	/**
	 * 后退
	 */
	$.back = function() {
		if (typeof $.options.beforeback === 'function') {
			if ($.options.beforeback() === false) {
				return;
			}
		}
		var assign = plus.webview.getWebviewById('assign.html');
		mui.fire(assign, 'refresh', {//触发页面自定义事件
			id: ''
		});
		
		var dynamic = plus.webview.getWebviewById('Dynamic_Child.html');
		mui.fire(dynamic, 'rebind', {//触发动态页面自定义事件
			id: ''
		});
		
		var person=plus.webview.getWebviewById("personal.html");
		mui.fire(person,'refresh',{});
		$.doAction('backs');
	};


})(mui, window);

function login() {
//	mui.toast("正在登录,请稍候...");
	$("#login").attr("disabled",true);
	var user = $("#account").val();
	//alert(user);
	if (user.trim() == "") {
		mui.toast("账号不能为空!");
		return;
	}
	var pwd = $("#password").val();
	if (pwd.trim() == "") {
		mui.toast("密码不能为空!");
		return;
	}
	var date = new Date().getMilliseconds();
	var newurl = "";
	var uuid=plus.device.uuid;
	newurl = server + "?action=loginin&username=" + user + "&password=" + pwd + "&date=" + date+"&uuid="+uuid;
//	console.log(newurl);
	$.getJSON(newurl, success);
};
var success = function(response) {
	//alert(response.success);
	var strresponse = JSON.stringify(response);

	if (response.success) {
		mui.toast("登录成功");
		plus.storage.setItem("policeid", response.policeid);//用户ID
		plus.storage.setItem("loginname", response.loginname);//警号
		plus.storage.setItem("community", response.community);//社区编号
		plus.storage.setItem("branchcode", response.branchcode);//部门编号
		plus.storage.setItem("realname", response.realname);//真实姓名
		plus.storage.setItem("uuid", response.uuid);//不解释
		plus.storage.setItem("branchname", response.branchname);//部门名称
		plus.storage.setItem("phone", response.phone);
		plus.storage.setItem("phoneshort", response.phoneshort);
		plus.storage.setItem("communityname", response.communityname);
		plus.storage.setItem("userimg", response.img);
		plus.storage.setItem("role", response.role);
		mui.openWindow({
			url: 'main.html',
			id: 'main',
			show: {
				autoShow: false
			}
		});
	} else {
		mui.toast(response.error); //自动消失的提示框
		$("#login").removeAttr("disabled");
	}
	
}

function savepic(){//预览时保存图片
	mui.toast('正在保存,请稍等');
//				console.log($(".mui-imageviewer-item").children().children().attr("src"));
	var picurl=$(".mui-imageviewer-item").children().children().attr("src");//需要自己去找到图片的路径
	var dtask = plus.downloader.createDownload(picurl, {}, function(d, status) {
		// 下载完成
		if (status == 200) {
			console.log("Download success: " + d.filename);
			plus.gallery.save(d.filename, function() {
				mui.toast('保存成功');
			}, function(error) {
				mui.toast('保存失败,请重试!');
				console.log(error.code+""+error.message);
			});
		} else {
			console.log("Download failed: " + status);
		}
	
	});
	dtask.start();
}

服务端用Node.js监听,核心代码如下:

/* var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 
  
app.get('/', function(req, res){ 
    res.send('

Welcome Realtime Server

'); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); */ var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); // 加载File System读写模块 var fs = require('fs'); app.get('/', function(req, res){ res.send('

聊天服务已启动

'); }); //在线用户 var onlineUsers = {}; //当前在线人数 var onlineCount = 0; io.on('connection', function(socket){ //console.log('一个用户连接'); /* var nowDate = new Date(); var result = nowDate.getFullYear()+"-"+((nowDate.getMonth()+1)<10?"0"+(nowDate.getMonth()+1):(nowDate.getMonth()+1))+"-"+(nowDate.getDate())+" "+ nowDate.getHours()+":"+nowDate.getMinutes()+":"+nowDate.getSeconds(); console.log(result); */ //var moment = require("moment");moment().format("YYYY-MM-DD HH:mm:ss") //监听新用户加入 socket.on('login', function(obj){ var dates=new Date().format("yyyy-MM-dd hh:mm:ss"); var file = "c:\\nodeLog.txt"; function writeFile(str){ // appendFile,如果文件不存在,会自动创建新文件 // 如果用writeFile,那么会删除旧文件,直接写新文件 //var datenow=moment().format("YYYY-MM-DD HH:mm:ss"); fs.appendFile(file, "["+dates+"]----"+str+"\n\r", function(err){ if(err) console.log("fail " + err); else console.log("写入文件ok:----"+str); }); } //将新加入用户的唯一标识当作socket的名称,后面退出的时候会用到 socket.name = obj.userid; writeFile("User Login:"+obj.userid); //检查在线列表,如果不在里面就加入 if(!onlineUsers.hasOwnProperty(obj.userid)) { onlineUsers[obj.userid] = obj.username; //在线人数+1 onlineCount++; } //writeFile("11111111111111111"); //向所有客户端广播用户加入 io.emit('login', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj}); //writeFile("22222222222222"); //console.log(obj.username+'加入了群组'); for(var i=0;i

其他就是相关的服务器配置文件了,剩余的,请自行百度。








你可能感兴趣的:(HTML5,MUI)