基于html5 localStorage , web SQL, websocket的简单聊天程序

new function() {
	var ws = null;
	var connected = false;

	var serverUrl;
	var connectionStatus;
	var sendMessage;
	
	var connectButton;
	var disconnectButton; 
	var sendButton;

	var open = function() {
		var url = serverUrl.val();
		ws = new WebSocket(url);
		ws.onopen = onOpen;
		ws.onclose = onClose;
		ws.onmessage = onMessage;
		ws.onerror = onError;

		localStorage.setItem("server", url);

		connectionStatus.text('OPENING ...');
		serverUrl.attr('disabled', 'disabled');
		connectButton.hide();
		disconnectButton.show();
	};
	
	var close = function() {
		if (ws) {
			console.log('CLOSING ...');
			ws.close();
		}
		connected = false;
		connectionStatus.text('CLOSED');

		serverUrl.removeAttr('disabled');
		connectButton.show();
		disconnectButton.hide();
		sendMessage.attr('disabled', 'disabled');
		sendButton.attr('disabled', 'disabled');

		loginName.attr('disabled', 'disabled');
		loginPass.attr('disabled', 'disabled');
		loginButton.attr('disabled', 'disabled');
	};
	
	var clearLog = function() {
		$('#messages').html('');
	};
	
	var login = function(event) {
		var name = loginName.val();
		var password = loginPass.val();
		if(name!= "" && password != ""){
			var msg= "login|"+ name + "|"+ password;
			ws.send(msg);

			localStorage.setItem("name", name);
			localStorage.setItem("password", password);			
		}else{
			alert("name and  password  cant't be empty!")
		}
	};


	var doLogin= function(msg){	
		if(msg.substr(0, 5)== "login"){
			sendMessage.removeAttr('disabled');
			sendButton.removeAttr('disabled');

			loginName.attr('disabled', 'disabled');
			loginPass.attr('disabled', 'disabled');
			loginButton.attr('disabled', 'disabled');

			return "login success!"
		}else if(msg.substr(0, 3)== "msg"){
			return msg.substr(4)
		}else{
		}
		return ""
	};

	var onOpen = function() {
		console.log('OPENED: ' + serverUrl.val());
		connected = true;
		connectionStatus.text('OPENED');

		//sendMessage.removeAttr('disabled');
		//sendButton.removeAttr('disabled');

		loginName.removeAttr('disabled');
		loginPass.removeAttr('disabled');
		loginButton.removeAttr('disabled');
	};
	
	var onClose = function() {
		console.log('CLOSED: ' + serverUrl.val());
		ws = null;
	};
	
	var onMessage = function(event) {
		var data = event.data;
		//login
		data= doLogin(data)
		//todo
		if(data){
			addMessage(data);
			//$('#messages').val("");
			//getLog();
			db.transaction(function (tx) {  
			  tx.executeSql('INSERT INTO LOGS (content) VALUES ("'+ data+ '")');
			});
		}
	};
	
	var onError = function(event) {
		alert("error, maybe socket closed!")
		//alert(event.data);
	};
	
	var addMessage = function(data, type) {
		var msg = $('<pre>').text(data);
		if (type === 'SENT') {
			msg.addClass('sent');
		}
		var messages = $('#messages');
		messages.append(msg);
		messages.append($("<br>"));
		
		var msgBox = messages.get(0);
		while (msgBox.childNodes.length > 10000) {
			msgBox.removeChild(msgBox.firstChild);
		}
		msgBox.scrollTop = msgBox.scrollHeight;
	};
	

	var getLog= function(start, limit){
			if(typeof(start) == undefined || !start){
				start= 0
			}
			if(typeof(limit) == undefined || !limit){
				limit= 10000
			}
			//log
			db.transaction(function (tx) {
				tx.executeSql('SELECT * FROM LOGS limit ?, ?', [start, limit], function (tx, results) {
				var len = results.rows.length, i;
				for (i = 0; i < len; i++){
				   msg = results.rows.item(i).content;
				   //document.querySelector('#status').innerHTML +=   msg;
				   //alert(msg)
				   addMessage(msg);
				 }
			 }, null);
			});
	};
	WebSocketClient = {
		init: function() {
			serverUrl = $('#serverUrl');
			connectionStatus = $('#connectionStatus');
			sendMessage = $('#sendMessage');
			
			connectButton = $('#connectButton');
			disconnectButton = $('#disconnectButton'); 
			sendButton = $('#sendButton');

			loginName= $('#name');
			loginPass= $('#password');
			loginButton= $('#loginButton');

			if(cache_server!= null)serverUrl.val(cache_server)
			if(cache_name!= null)loginName.val(cache_name)
			if(cache_password!= null)loginPass.val(cache_password)

			getLog();

			loginButton.click(function(e) {
				login();
			});
			
			connectButton.click(function(e) {
				close();
				open();
			});
		
			disconnectButton.click(function(e) {
				close();
			});
			
			sendButton.click(function(e) {
				var msg = $('#sendMessage').val();
				if(msg== "" ){
					alert("You must say something!")
				}else{
					ws.send("msg|"+ msg);
					$('#sendMessage').val("")
				}
			});
			
			$('#clearMessage').click(function(e) {
				clearLog();
			});
			
			var isCtrl;
			sendMessage.keyup(function (e) {
				if(e.which == 17) isCtrl=false;
			}).keydown(function (e) {
				if(e.which == 17) isCtrl=true;
				if(e.which == 13 && isCtrl == true) {
					sendButton.click();
					return false;
				}
			});
		}
	};
}

$(function(){
	cache_server= localStorage.getItem("server")
	cache_name= localStorage.getItem("name")
	cache_password= localStorage.getItem("password")	

	db = openDatabase('mydb', '1.0', 'Test DB', 5 * 1024 * 1024);

	db.transaction(function (tx){
		tx.executeSql("CREATE TABLE IF NOT EXISTS LOGS ('id' integer primary key autoincrement,'content' text)");
	 });

	WebSocketClient.init();

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值