现在的位置: 首页 > 综合 > 正文

WebSocket+Node.js 通讯及在 iPhone中 实现

2013年12月10日 ⁄ 综合 ⁄ 共 5262字 ⁄ 字号 评论关闭

最近在研究搜集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的别人的代码~):

var http = require('http');  
http.createServer(function (req, res) {  
  res.writeHead(200, {'Content-Type': 'text/plain'});  
  res.end('Hello Node.js!!');  
  }).listen(8124, "127.0.0.1");  
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安装

cd 你解压的路径
./configure     
make
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

var conns = new Array();
var ws = require('./lib/ws/server');
var server = ws.createServer();

server.addListener('connection', function(conn){
console.log('New Connection:'+conn.id);
conns.push(conn);
conn.send(conn.id+" is your Connection ID: ");
conn.addListener('message',function(msg){
/* output the new message sent from client*/
        console.log(conn.id+':'+msg);
        var megContent = conn.id
for(var i=0; i<conns.length; i++){
if(conns[i]!=conn){
conns[i].send(conn.id+':'+msg);
}
}
        conn.send('self:'+msg);
});
});

server.listen(8080);
console.log('running......');

这里我想说的是,

var ws = require('./lib/ws/server');
这个是websocket的模块概念,./代表是同目录下的lib文件,所以你需要保证你的服务器js文件和lib在同一目录下,我的文件目录是这样的

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

<!DOCTYPE html>
<html> 
<head> 
<title>Web Socket Chat</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var host = '127.0.0.1';
    var port = 8080;
    var url = 'ws://'+host+':'+port+'/';
    var ws;
    $(document).ready(function () {

        if ("WebSocket" in window) {
            debug("Browser supports web sockets!", 'success');
            
            connect(url);
            $('#console_send').removeAttr('disabled');
        } else {
            debug("Browser does not support web sockets", 'error');
        };

        // function to send data on the web socket
        function ws_send(str) {
            try {
                ws.send(str);
            } catch (err) {
                debug(err, 'error');
            }
        }

        // connect to the specified host
        function connect(host) {

            debug("Connecting to " + host + " ...");
            try {
                ws = new WebSocket(host); // create the web socket
            } catch (err) {
                debug(err, 'error');
            }
            $('#host_connect').attr('disabled', true); // disable the 'reconnect' button

            ws.onopen = function () {
                debug("connected... ", 'success'); // we are in! :D 
            };

            ws.onmessage = function (evt) {
                debug(evt.data, 'response'); // we got some data - show it omg!!
            };

            ws.onclose = function () {
                debug("Socket closed!", 'error'); // the socket was closed (this could be an error or simply that there is no server)
                $('#host_connect').attr('disabled', false); // re-enable the 'reconnect button
            };
        };

        // function to display stuff, the second parameter is the class of the <p> (used for styling)
        function debug(msg, type) {
            $("#console").append('<p class="' + (type || '') + '">' + msg + '</p>');
        };

        // the user clicked to 'reconnect' button
        $('#host_connect').click(function () {
            debug("\n");
            connect($('#host').val());
        });

        // the user clicked the send button
        $('#console_send').click(function () {
            ws_send($('#console_input').val());
        });
		
        $('#console_input').keyup(function (e) {
            if(e.keyCode == 13) // enter is pressed
                ws_send($('#console_input').val());
        });

    });
</script> 
 
<style type="text/css"> 
	.error {color: red;}
	.success {color: green;}
	#console_wrapper {background-color: black; color:white;padding:5px;}
	#console p {padding:0;margin:0;}
</style> 
</head> 
 
<body> 
 
<h1>Web Socket Chat</h1> 
 
<div id="server_wrapper"> 
	<p>Server
		<input type="text" name="host" id="host" value="ws://localhost:8080/" /> 
		<input type="submit" name="host_connect" id="host_connect" value="重新连接" /> 
	</p>
</div> 
 
<div id="console_wrapper"> 
	<pre id="console"></pre> 
	<input type="text" name="console_input" id="console_input" value="" /> 
	<input type="submit" name="console_send" id="console_send" value="Send" /> 
</div> 
 
</body> 
 
</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与页面互相通讯的示例。

最后效果图:

【上篇】
【下篇】

抱歉!评论已关闭.