IOS: Socket-based third-party framework Cocoaasyncsocket usage

Source: Internet
Author: User
Tags uikit

Cocoaasyncsocket is undoubtedly the most well-packaged socket library now: Support asynchronous TCP/UDP, support Gcd,objective-c interface encapsulation, as well as log tracking function, using this log tracking, programmers can easily debug.

The file is as follows:

If you want to turn on log debugging, it is easy to import the required DDASLLogger.h header files and create Ddasllogger simple interest objects.

The simple demo is as follows:

1. In the story version layout

2. In the ViewController.h file

 //  ViewController.h  //  Aysnsocket   #import  <uikit /uikit.h> #import   asyncsocket.h    @interface  Span style= "color: #000000;"    > viewcontroller:uiviewcontroller{Nsmutablearray  *_scokets; //     store variable array of clients     Asyncsocket *_sendsocket; //     send side     Asyncsocket *_recescoket; //  receive end     @end  

3. In the viewcontroller.m file

//VIEWCONTROLLER.M//Aysnsocket#import "ViewController.h"#import "AsyncSocket.h"@interfaceViewcontroller () @property (weak, nonatomic) Iboutlet Uitextview*Msgview, @property (weak, nonatomic) Iboutlet Uitextfield*Ipfield, @property (weak, nonatomic) Iboutlet Uitextfield*Sendfield;-(Ibaction) coneclicked: (UIButton *) sender;//connecting to a server-(Ibaction) sendclicked: (UIButton *) sender;//Send side Send message-(Ibaction) disconeclicked: (UIButton *) sender;//Disconnect Connection@end@implementationViewcontroller@synthesizeMsgview;@synthesizeIpfield;@synthesizeSendfield;- (void) viewdidload {[Super viewdidload]; //1. Initialize the scokets array and store the new client Scoket_scokets =[Nsmutablearray array]; //2. Instantiate the sending and receiving end_sendsocket =[[Asyncsocket alloc]initwithdelegate:self]; _recescoket=[[Asyncsocket alloc]initwithdelegate:self]; //3. The receiving end starts to listen to the networkNserror *error; [_recescoket Acceptonport:8888error:&error];}#pragmaMark-Proxy method//to receive a new scoket.- (void) Onsocket: (Asyncsocket *) sock didacceptnewsocket: (Asyncsocket *) newsocket{//Add the newly received socket to the array[_scokets Addobject:newsocket]; //Start accepting Data[Newsocket readdatawithtimeout:-1Tag0];}//Received information from the receiving end- (void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (Long) tag{//Receive DataNSString *string=[[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]; //Formatting DataSelf.msgView.text = [NSString stringWithFormat:@"%@,%@,%@", Self.msgview.text,self.ipfield.text,string]; //Loop Read[Sock readdatawithtimeout:-1Tag0];}//Connection Server succeeded- (void) Onsocket: (Asyncsocket *) sock didconnecttohost: (NSString *) host port: (UInt16) port{NSLog (@"%@", host); NSLog (@"Connection Server succeeded");}//Disconnected Server succeeded-(void) Onsocketdiddisconnect: (Asyncsocket *) sock{NSLog (@"Disconnected successfully");}#pragmaMark-button Event//Establish a connection-(Ibaction) coneclicked: (UIButton *) Sender {if(_sendsocket.isconnected) {[_sendsocket disconnect]; }        //client Reconnect to host[_sendsocket connectToHost:self.ipField.text OnPort:8888Withtimeout: -Error:nil];}//Send Message-(Ibaction) sendclicked: (UIButton *) Sender {//client sends dataNSData *data =[Self.sendField.text datausingencoding:nsutf8stringencoding]; [_sendsocket writedata:data withtimeout: -Tag0]; //Clear DataSelf.sendField.text =@"";}//disconnecting the server-(Ibaction) disconeclicked: (UIButton *) sender{if(_sendsocket.isconnected) {[_sendsocket disconnect]; }}@end

The test is as follows:

(1) Open the computer's network settings, look at the IP and set the port to 8888

(2) Run the program and enter the IP and message in the demo

Start: Enter IP and messages, and then connect to the server

Successfully sent a successful connection to a successful server

To disconnect the server:

After disconnecting the server, the attempt to send the data is not sent and displayed on the Uitextview.

IOS: Socket-based third-party framework Cocoaasyncsocket usage

Related Article

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.