JSON data transfer and acquisition of socket communication

Source: Internet
Author: User

This article is based on the Scoket communication TCP to carry out the JSON format of data transmission and acquisition.

First, we first download the Asyncsockethttps://github.com/robbiehanson/cocoaasyncsocket class library, the Runloop folder under the AsyncSocket.h, ASYNCSOCKET.M, AsyncUdpSocket.h, asyncudpsocket.m files are copied to your own project.

Then add the Cfnetwork.framework Kit to your project.

Then start creating the connection with the following code:

Scoket=[[asyncsocket Alloc]initwithdelegate:self]; Initialization

[Scoket connecttohost:@ "host port" Onport:port Error:nil];

For example:

[Scoket connecttohost:@ "192.168.10.128" onport:4001 Error:nil];

Click Connecttohost to view the specific steps of the connection.

After you create the connection, import the agent header header @interface Viewcontroller () <AsyncSocketDelegate> Use the following proxy method:

Agent Method 1: See if Scoket is connected successfully

-(void) Onsocket: (Asyncsocket *) sock didconnecttohost: (NSString *) host port: (UInt16) port{

NSLog (@ "connected successfully");

[Scoket readdatawithtimeout:timezone tag:1];//receive data

Heartbeat Pack

_connecttimer=[nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (Longconnecttoscoket) Userinfo:nil Repeats:yes];

}

The Longconnecttoscoket method is implemented as follows:

Heartbeat Packet Long Connection

-(void) longconnecttoscoket{

[Scoket readdatawithtimeout:timezone tag:1];//receive data

}

Next is the encapsulation, sending, and receiving of the data:

-(void) clickpublish{

[Email protected] {

@ "User": @ "Linda",//user name

@ "Museum": @ "1",//Museum name

@ "Content": Commentfield.text//Comments

};

Dictionary converted to string

NSData *jsondata = [nsjsonserialization datawithjsonobject:dic options:nsjsonwritingprettyprinted Error:nil];

Str=[[nsstring alloc] Initwithdata:jsondata encoding:nsutf8stringencoding];

Encapsulating data

NSData *commentdata=[str datausingencoding:nsutf8stringencoding];

[Scoket writedata:commentdata withtimeout:10 tag:1];//Send data

[Scoket readdatawithtimeout:30 tag:1];//receive data

commentfield.text=nil;//Empty Comment bar content

}

To process the acquired data:

-(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag{

NSLog (@ "data:%@", data);

NSString *message=[[nsstring Alloc]initwithdata:data encoding:nsutf8stringencoding];

NSLog (@ "message:%@", message);

Convert a string to a dictionary

NSData *jsondata = [message datausingencoding:nsutf8stringencoding];

Nsdictionary *dic1=[nsjsonserialization jsonobjectwithdata:jsondata options:nsjsonreadingmutablecontainers Error: NIL];

Str1=[dic1 objectforkey:@ "Content"];//gets the value corresponding to the key

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

Send a notification

[[Nsnotificationcenter defaultcenter]postnotificationname:@ "Change" object:str1];

}

Notification receive, where _allcomments is a mutable array

-(void) receivenotify{

Registration Notice

[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (message:) name:@ "Change" object:nil];

}

Registration Notification method

-(void) message: (Nsnotification *) note{

NSString *str=[[nsstring Alloc]init];

str = note.object;

_allcomments=[[nsmutablearray Alloc]init];

[_allcomments ADDOBJECT:STR];

[Self start];

}

JSON data transfer and acquisition of socket communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.