iOS Client 与WebSocket 通信 入门demo 即时通讯 socketio

来源:互联网 发布:这个淘宝内衣女模特赵 编辑:程序博客网 时间:2024/04/29 16:27

转自 http://www.xuebuyuan.com/1681902.html

1.首先去node js 官网安装node js环境

 

  安装完成 打开终端 输入 : node  -v

   log输出:v0.10.13. 

   这就证明你的node环境好了。

 

    2..在socket io 官网下载下载socket io的例子,直接copy保存为js文件就好,取名为app.js。


    3. 把你新建的app.js copy到 刚才node js 安装的目录下(注意路径)

    /usr/local/lib目录下,注意这个目录是系统隐藏的目录

   4.打开终端cd 到这个目录下 输入:node  app.js

   看看会不会报错。正常情况下是

输出:  info  -  socket. io  started

如果报错那就可能还缺少2个插件,express 和 ejs 


分别输入 :sudo npm install express

                         sudo npm install ejs


 


然后再次运行node  app.js

就看见输出:  info  -  socket. io  started


  下面这边websocket的环境已经ok了。

 然后就看ios这边的了。 在github 下载我的demo app 然后直接运行就好了,可以看见下面的效果了。

具体代码重点是初始化一个socketio的对象,然后实现他的delegate:


    

    socketIO = [[SocketIO alloc] initWithDelegate:self];

    //socketIO.useSecure = YES;

    [socketIO connectToHost:@"localhost" onPort:8127];  

 然后在发送就条用这个方法:


-(void)sendMessageToWebSocket:(NSString *)str

{

    SocketIOCallback cb = ^(id argsData) {

        NSDictionary *response = argsData;

        // do something with response

        NSLog(@"ack arrived: %@", response);

    };

    [socketIO sendMessage:str withAcknowledge:cb];

}


客户端接受到消息

- (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet

{

    NSLog(@"didReceiveEvent()");

    NSString *receiveData=packet.data;

    NSData *utf8Data = [receiveData dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *dictemp=(NSDictionary *)[SocketIOJSONSerialization objectFromJSONData:utf8Data error:nil];

    NSDictionary *aadic=(NSDictionary *)[[dictemp objectForKey:@"args"] objectAtIndex:0];

    NSString * temp = [aadic objectForKey:@"text"];

    

    NSLog(@"temp==%@",temp);

    if (![temp isEqualToString:@"connectok"]) {

        [self.messages addObject:temp];

        

        if((self.messages.count - 1) % 2)

            [MessageSoundEffect playMessageSentSound];

        else

            [MessageSoundEffect playMessageReceivedSound];

        

        [self finishSend];

    }

    

}


 

 

 

Demo下载地址

0 0
原创粉丝点击