首页 > 代码库 > 基于html5 localStorage , web SQL, websocket的简单聊天程序

基于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 = one rror;

		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 = http://www.mamicode.com/event.data;>

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