Instant Messaging sockets for iOS development (Asyncsocket)

Source: Internet
Author: User

1, Asyncsocket Introduction If you need to do instant communication in the project like QQ, you must use socket communication. How sockets are programmed in iOS: The BSD SOCKET:BSD socket is a common network interface in UNIX systems that not only supports a variety of network types, but is also a communication mechanism between internal processes. The iOS system is essentially UNIX, so it can be used, but more complex. Cfsocket:cfsocket is the way Apple provides us with a socket, but it's not very handy. Of course, if you want to use it, you can study it carefully. Asyncsocket: The third-party open Source Library, the preferred way, is also often used in development projects. The reason to choose Asyncsocket: iphone cfnetwork programming is more complex. Using the Asyncsocket open Source library for development is relatively simple and helps us encapsulate a lot of things. Environment: Download the Asyncsocket:https://github.com/robbiehanson/cocoaasyncsocket class library, the Runloop folder AsyncSocket.h, ASYNCSOCKET.M, Copy AsyncUdpSocket.h, asyncudpsocket.m files to your own project to add Cfnetwork.framework, and then use the socket header #import <sys/socket.h > #import <netinet/in.h> #import <arpa/inet.h> #import <unistd.h>2, asyncsocket in actual development, The main task is to develop the client. So the following is the main explanation of the client's entire connection establishment process, and what functions are recalled at the time of the description. Common methods: 1, establish the connection-(int) ConnectServer: (NSString *) hostip port: (int) HostPort2, after the connection succeeds, the function that will callback-(void) Onsocket: (Asyncsocket *) Sock didconnecttohost: (NSString *) host port: (UInt16) PORT3, send data-(void) WriteData: (NSData *) data withtimeout: ( Nstimeinterval) Timeout tag: (long) tag;4, accept data-(void) ONSOCKET: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) Tag5, disconnected-(void) Onsocket: (Asyncsocket *) sock Willdisconnectwitherror: (Nserror *) err-(void) Onsocketdiddisconnect: (Asyncsocket *) sock is mainly a few of the above methods, just said in the real development, It is likely that when we send and receive data, the data we send and receive is not just a string wrapped into nsdata, we are likely to send a struct and other types, and this time we need to collaborate with the server side to develop: define what kind of structure. 3, the use of a detailed description of the real-time communication is the most important feature of realtime, the basic sense is not delayed or dropped, so the connection to the socket must be monitored and detected, when the disconnection, reconnect, if the user log out, to the socket manually shut down, or the server will cause a certain load. In general, a user (for iOS, our project) can have only one socket connected, so the socket variable must be global, here you can consider using singleton or appdelegate for data sharing, preferred to use a singleton. If a connected socket object is connected again, it throws an exception (no connection to the connected socket) crashes, so the connection state of the socket object is judged before the socket is connected. Using the socket for Instant messaging There is also a necessary operation, that is, sending a heartbeat packet to the server, sending long connection instructions to the server at intervals (instructions are not unique, specified by the server, including sending messages using the socket, sending data and formats are specified by the server), If you do not receive a return message from the server, Asyncsocket will get the message of the lost connection, and we can reconnect in the lost connection callback method. Declare the socket variable: @property (nonatomic, strong) Asyncsocket *socket; Socket @property (nonatomic, copy) NSString *sockethost; Socket host @property (nonatomic, assign) UInt16 Socketport; Socket prot Connection (long connection)-(void) socketconnecthost;//socket connection, both host and port are specified by the server. Socket connection-(void) Socketconnecthost{self.socket = [[Asyncsocket alloc] initwithdelegate:self]; Nserror *error = nil; [Self.socket connectToHost:self.socketHost onPort:self.socketPort withtimeout:3 error:&error];} Heartbeat through the timer to achieve @property (nonatomic, retain) Nstimer *connecttimer; The timer implements a method of connecting a successful callback, initializes the timer in this method, periodically sends a request to the server, keeps the connection #pragma mark-the connection succeeded callback-(void) Onsocket: (Asyncsocket *) sock Didconnecttohost: (NSString *) host port: (UInt16) port {NSLog (@ "Socket successful"),//30s heartbeat packet sent to/from server Self.connecttimer = [ Nstimer scheduledtimerwithtimeinterval:30 target:self selector: @selector (longconnecttosocket) Userinfo:nil repeats: yes];//the message sent to the server for a long connection in the Longconnecttosocket method [Self.connecttimer fire]; Disconnect: There are several cases of loss of connectivity, the server is disconnected, the user active cut, but also may be like QQ other device login is dropped, regardless of that situation, we can receive the socket callback method returned to our message, if the user is logged out or the program exits the need for manual cut, We assign a value to the userdata of the socket before the cut to mark it as a user exit, so that we can determine what is causing the drop when we receive the break information an enumeration type is declared in the. h file enum{socketofflinebyserver,// Server drop line, default is 0SocketOfflineByUser,//user active Cut}; Define and implement Break Method-(void) CutoffsockEt Disconnect the socket//Cut socket-(void) Cutoffsocket{self.socket.userdata = socketofflinebyuser;//Declaration is initiated by the user to cut [ Self.connecttimer invalidate]; [Self.socket disconnect];} The re-connect implements the Proxy method-(void) Onsocketdiddisconnect: (Asyncsocket *) sock {NSLog (@ "Sorry the Connect is failure%ld", sock.userdata); (Sock.userdata = = socketofflinebyserver) {//server dropped, re-connected [self socketconnecthost];}      else if (Sock.userdata = = Socketofflinebyuser) {//If disconnected by the user, do not re-connect return; }} Send data: We add the above method of heartbeat connection not completed//heartbeat connection-(void) longconnecttosocket{//according to server requirements to send a fixed format of data, assuming the directive @ "Longconnect", But generally not so simple instructions nsstring *longconnect = @ "Longconnect"; NSData *datastream = [Longconnect datausingencoding:nsutf8stringencoding]; [Self.socket writedata:datastream withtimeout:1 tag:1];} Socket send data is stored in the form of a stack, all data placed in a stack, access will appear sticky packet phenomenon, so many times the server in sending and receiving data is to send the content byte length, and then send the form of content, get the data is also first to get a length, Then according to this length in the stack to read this length of the byte stream, if this is the case, send the data only need to send a length before sending the content, the sending method is the same as the sending content, assuming a length of 8NSData *datastream = [@8 datausingencoding: Nsutf8stringencoding]; [Self.socket writedata:datastream withtimeout:1 tag:1]; Receive numberAccording to: In order to receive the message of the socket at all times, we read the data in the long connection method [Self.socket readdatawithtimeout:30 tag:0]; If you get the data, call the callback method:-(void) Onsocket: ( Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag {//The resulting data value can be parsed and converted [Self.socket Readdatawithtimeout:30 tag:0];} Remarks about NSData objects regardless of whether the socket is sent or received by the NSData object. The NSData is primarily a data space and length with a (ID) that is pointed to. NSString converted to NSData object nsdata* xmlData = [@ "testdata" datausingencoding:nsutf8stringencoding]; NSData converted to NSString object NSData * data; NSString *result = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];

Instant Messaging sockets for iOS development (Asyncsocket)

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.