[转载]WebSocket+Node.js 通讯及在 iPhone中 实现

来源:互联网 发布:安卓数据恢复软件 apk 编辑:程序博客网 时间:2024/05/22 14:03

最近在研究搜集HTML5的WebSocket.

公司的新项目是想在iPhone上实现WebSocket实时通讯.所以我翻了翻HTML5概念,知道WebSocket是HTML5的特性。

一路又看了看WebSocket,然后又了解了一下Node.js,都是浅层的概念上的查找,因为之前只是会议听boss提过,没有动手用过。

于是,开始了尝试如何在Macintosh上实现WebSocket+Node.js+iPhone UiWebView。其实我只是修改了一些代码,99%都是copy别人的...

(可以跳到言归正传里看技术相关,以下为个人感想)

先不说我是在各种资料各种代码各种语言间的辗转,我想记下过程的感想,因为,最后实现的时候我瞬间的喜悦伴随的是自己的一些零散感受。

首先,查找别人的总结时,要细致,不要走马观花,我就总是有这个习惯,最后稀里糊涂弄下来,90%是画不出葫芦的,瓢都谈不上。

其次,保持好的乐观的心态。实现这个简单的东西,我用了两天半,虽然都是每天用两三个小时,但是也感觉花了不少功夫,但效率太低。

最后,即时总结,多动脑袋,少盲从,因为别人的代码和资料一般都是有时间条件限制的,别人能调通的code,到你的环境和语言下就是有各种错误,这时候要镇定啊!!!

细心加耐心,慢慢来吧~

---------------------------------------------------------------华丽的分割线啊~~-------------------------------------------------------------------------------------------------------------------------------------------

言归正传

我使用的是Macintosh,系统是Mac OS X 10.6.8   浏览器用safari,chrome不给力,困扰了我一天,最后发现是我用得模块代码不支持它...各种哭泣,然后决定以后环境一定要弄清再用!

同样参考 

http://my.oschina.net/lionyang/blog/30410  这个资源里我使用的是作者的服务器端现成代码。

http://www.cnblogs.com/meteoric_cry/archive/2011/06/05/2073226.html    这个资源里我使用的是客户端现成代码,服务器端代码调试失败,不知道什么原因,可能是我人品问题在家上个人理解问题...

是我实现过程中参考的比较有用的博客文章

Step1:安装Node.js环境

参考这里:http://howtonode.org/how-to-install-nodejs#hello

在terminal里输入(这个需要有安装git,我很久之前安装的,应该很简单,这个我就不考究了)

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

安装好后,可以Test一下是否安装成功 

在node目录下创建一个javascript脚本,比如叫hello.js

代码如下(这个也是copy的别人的代码~):

  1. var http = require('http');    
  2. http.createServer(function (req, res) {    
  3.   res.writeHead(200, {'Content-Type''text/plain'});    
  4.   res.end('Hello Node.js!!');    
  5.   }).listen(8124, "127.0.0.1");    
  6. console.log('Server running at http://127.0.0.1:8124/');  


然后terminal里会输出:Server running at http://127.0.0.1:8124/

现在你把    http://127.0.0.1:8124/       在浏览器其中打开如果看到Hello Node.js!!,恭喜你,Node.js你安装成功鸟!

Step 2:

安装npm Node.js 包管理工具

去下载最新版本的压缩文件,解压后用terminate安装

  1. cd 你解压的路径  
  2. ./configure       
  3. make  
  4. sudo make install  


Step 3:

安装websocket-server模块,WebSocket里有模块化结构的概念,(具体参考

http://developer.51cto.com/art/201107/278586.htm  )

这其实是一个别人写好的封装,想进行WebSocket通讯可以直接在此基础上从coding。

在npm路径下,用terminal安装 官网资料    http://static.brandedcode.com/nws-docs/

npm install websocket-server

Final Step:

ok,现在需要安装的准备就这些了~现在开始实现代码通讯。

服务器端代码:serv.js

  1. var conns = new Array();  
  2. var ws = require('./lib/ws/server');  
  3. var server = ws.createServer();  
  4.   
  5. server.addListener('connection'function(conn){  
  6. console.log('New Connection:'+conn.id);  
  7. conns.push(conn);  
  8. conn.send(conn.id+" is your Connection ID: ");  
  9. conn.addListener('message',function(msg){  
  10. /* output the new message sent from client*/  
  11.         console.log(conn.id+':'+msg);  
  12.         var megContent = conn.id  
  13. for(var i=0; i<conns.length; i++){  
  14. if(conns[i]!=conn){  
  15. conns[i].send(conn.id+':'+msg);  
  16. }  
  17. }  
  18.         conn.send('self:'+msg);  
  19. });  
  20. });  
  21.   
  22. server.listen(8080);  
  23. console.log('running......');  

这里我想说的是,

  1. var ws = require('./lib/ws/server');  
  1. 这个是websocket的模块概念,./代表是同目录下的lib文件,所以你需要保证你的服务器js文件和lib在同一目录下,我的文件目录是这样的  
  1. <img src="http://hi.csdn.net/attachment/201110/10/0_1318234335rRqh.gif" alt="">  


客户端代码index.html (这里还使用了jQuery,文件jquery-1.3.2.min.js一起使用)

  1. <!DOCTYPE html>  
  2. <html>   
  3. <head>   
  4. <title>Web Socket Chat</title>  
  5. <meta http-equiv="content-type" content="text/html;charset=utf-8">  
  6.   
  7. <script src="jquery-1.3.2.min.js" type="text/javascript"></script>  
  8. <script type="text/javascript">  
  9.     var host = '127.0.0.1';  
  10.     var port = 8080;  
  11.     var url = 'ws://'+host+':'+port+'/';  
  12.     var ws;  
  13.     $(document).ready(function () {  
  14.   
  15.         if ("WebSocket" in window) {  
  16.             debug("Browser supports web sockets!", 'success');  
  17.               
  18.             connect(url);  
  19.             $('#console_send').removeAttr('disabled');  
  20.         } else {  
  21.             debug("Browser does not support web sockets", 'error');  
  22.         };  
  23.   
  24.         // function to send data on the web socket  
  25.         function ws_send(str) {  
  26.             try {  
  27.                 ws.send(str);  
  28.             } catch (err) {  
  29.                 debug(err, 'error');  
  30.             }  
  31.         }  
  32.   
  33.         // connect to the specified host  
  34.         function connect(host) {  
  35.   
  36.             debug("Connecting to " + host + " ...");  
  37.             try {  
  38.                 ws = new WebSocket(host); // create the web socket  
  39.             } catch (err) {  
  40.                 debug(err, 'error');  
  41.             }  
  42.             $('#host_connect').attr('disabled', true); // disable the 'reconnect' button  
  43.   
  44.             ws.onopen = function () {  
  45.                 debug("connected... ", 'success'); // we are in! :D  
  46.             };  
  47.   
  48.             ws.onmessage = function (evt) {  
  49.                 debug(evt.data, 'response'); // we got some data - show it omg!!  
  50.             };  
  51.   
  52.             ws.onclose = function () {  
  53.                 debug("Socket closed!", 'error'); // the socket was closed (this could be an error or simply that there is no server)  
  54.                 $('#host_connect').attr('disabled', false); // re-enable the 'reconnect button  
  55.             };  
  56.         };  
  57.   
  58.         // function to display stuff, the second parameter is the class of the <p> (used for styling)  
  59.         function debug(msg, type) {  
  60.             $("#console").append('<p class="' + (type || '') + '">' + msg + '</p>');  
  61.         };  
  62.   
  63.         // the user clicked to 'reconnect' button  
  64.         $('#host_connect').click(function () {  
  65.             debug("\n");  
  66.             connect($('#host').val());  
  67.         });  
  68.   
  69.         // the user clicked the send button  
  70.         $('#console_send').click(function () {  
  71.             ws_send($('#console_input').val());  
  72.         });  
  73.           
  74.         $('#console_input').keyup(function (e) {  
  75.             if(e.keyCode == 13) // enter is pressed  
  76.                 ws_send($('#console_input').val());  
  77.         });  
  78.   
  79.     });  
  80. </script>   
  81.    
  82. <style type="text/css">   
  83.     .error {color: red;}  
  84.     .success {color: green;}  
  85.     #console_wrapper {background-color: black; color:white;padding:5px;}  
  86.     #console p {padding:0;margin:0;}  
  87. </style>   
  88. </head>   
  89.    
  90. <body>   
  91.    
  92. <h1>Web Socket Chat</h1>   
  93.    
  94. <div id="server_wrapper">   
  95.     <p>Server  
  96.         <input type="text" name="host" id="host" value="ws://localhost:8080/" />   
  97.         <input type="submit" name="host_connect" id="host_connect" value="重新连接" />   
  98.     </p>  
  99. </div>   
  100.    
  101. <div id="console_wrapper">   
  102.     <pre id="console"></pre>   
  103.     <input type="text" name="console_input" id="console_input" value="" />   
  104.     <input type="submit" name="console_send" id="console_send" value="Send" />   
  105. </div>   
  106.    
  107. </body>   
  108.    
  109. </html>  



在terminal里开启服务端

用safari打开客户端index.html


可以打开多个,互相通讯.

现在,我们要移植到ios UIWebView 中,我的工程代码和nodejs代码在cocoachina里分享。

地址:http://www.cocoachina.com/bbs/post.php?action=modify&fid=6&tid=77707&pid=tpc&article=0

其实就是把index.html在UIWebView中加载,这里,把脚本和样式表分开。

还有如何在UIWebView与页面互相通讯的示例。


最后效果图:



0 0