/ walking bear:D / WebSocket-driver + EventEmitter

WebSocket-driver + EventEmitter

2017-04-23 posted in []

因為 中華電海纜斷線 連美、日網速尖峰延遲導致 npm install socket.io 整個卡住,無法下載 package。不想一個晚上無所事事,嘗試繞過 https://registry.npmjs.org/ ,改用 linux distribution 已經安裝的 node.js packages,雖然數量較少,版本也較老舊,但可以視為 node.js 的核心套件。 在 browser 端,不用 socket.io,意思是不能用 <script src="/socket.io/socket.io.js"></script> 抓進 socket.io 的 library。必須改採最基本的 html5 WebSocket class,程式片段如下:

	
	window.addEventListener("load", function() {
		var input = document.getElementById("input");
		var output = document.getElementById("output");
		output.log = function(msg) {
			var pre = document.createElement("p");
			pre.style.wordWrap = "break-word";
			pre.style.padding = "8px";
			pre.style.background = "#eee";
			pre.innerHTML = msg.replace(/\n/g, "<br/>");
			this.appendChild(pre); 
		};
		var wsUri = "ws://"+window.location.hostname+":"+window.location.port;
		var wsObj = new WebSocket(wsUri);
        wsObj.onopen = function(evt) { output.log(wsUri + " CONNECTED");  };
        wsObj.onclose = function(evt) { output.log("DISCONNECTED");  };
        wsObj.onmessage = function(evt) { output.log('RESPONSE: ' + evt.data+'');  };
        websocket.onerror = function(evt) { output.log('ERROR: ' + evt.data);  };
        document.getElementById("btn_close").addEventListener("click", function(e) {
        	e.preventDefault();
            wsObj.close(); 
		});
        document.getElementById("btn_send").addEventListener("click", function(e) {
			e.preventDefault();
			output.log("SENT: " + message.length);
    		wsObj.send(message); 
            input.value = "";
		});
	}, false);

. reply_count: 1 get_replies : 1 . 2017-04-23_16:02:01 wkliang 這篇問答 Misconceptions: Differences between socket.io and websockets ,比較了 socket.io 跟原味 websocket 之間的差異。socket.io 就像手搖飲料,添加了不少額外的元素,ex:flash, ajax polling… 如果單純鎖定 html5 browser,這些添加物可能只是造成肥大、低效、等後遺症。不用 socket.io 就要自己用 websocket-driver + events.EventEmitter 去兜出相關的功能,仍在努力中….. websocket-driver 每 60 secs 加 ping,否則每兩分鐘 browser 會自動斷開… .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll