On the instant communication programming to choose which way, the author used a socket to write a QQ chat communication application, by the way use this application to introduce a socket use it
The difference between the socket and XMPP is that both the client and server side of the socket need to be built themselves. XMPP has a ready-made server and client, writing test is relatively easy, so, XMPP has become the mainstream of real-time communication programming. But in the personal interest, socket is worth exploring.
All right, so much for that. The following is the author's socket application.
First introduce the client this is the client login interface
Next, register the operation
Click Register-( send a registration message to the server---the code below )
Client-registered user information is saved on the server-side database
Enter the user name you just registered, password login
Login page code Remember to import the asyncsocket framework First
#import <UIKit/UIKit.h> #import "AsyncSocket.h" typedef void (^issuccessblock) (BOOL); @interface Viewcontroller: uiviewcontroller{ __weak iboutlet UIView *_contbgview; Login View __weak iboutlet Uitextfield *_usernamefield; __weak iboutlet Uitextfield *_pwdfield; __weak iboutlet UITableView *_tableview; __weak iboutlet UIView *_sendview; Information text __weak iboutlet Uitextfield *_message;} @property (Nonatomic,strong) Asyncsocket *socket; Client Communication Object @property (nonatomic,copy) Issuccessblock block; Login successful authentication block//send Message-(ibaction) SendMessage: (UIButton *) sender;//Authentication User-(Ibaction) Contentaction: (UIButton *) sender;/ /Registered User-(ibaction) Registeraction: (UIButton *) sender; @end
#import "ViewController.h" #import "MyCell.h" #import "RegisterViewController.h" @interface Viewcontroller () < uitableviewdatasource,uitableviewdelegate,asyncsocketdelegate>//Set Communication Agent {Nsmutablearray *DATAARR;// Store this client and other client messages NSString *username; Verify the user name passed after} @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; [email protected] "cheep"; _contbgview.backgroundcolor=[uicolor colorwithpatternimage:[uiimage imagenamed:@ "Red.jpg"]; Dataarr=[nsmutablearray array]; _tableview.backgroundcolor=[uicolor colorwithpatternimage:[uiimage imagenamed:@ "Chat_bg_default.jpg"]; _tableview.separatorstyle=uitableviewcellseparatorstylenone; _tableview.rowheight=64; _sendview.backgroundcolor=[uicolor colorwithpatternimage:[uiimage imagenamed:@ "Chat_bottom_textfield.png"]; iOS Socket Third party framework Asyncsocket usage profile, connection, heartbeat, disconnection, data send and receive/* 1. Socket Connection 2. The socket disconnects and re-connects 3. The socket sends and receives data 4. Simple instructions for use */if (_socket = = nil) { _socket=[[asyncsocket alloc] initwithdelegate:self]; Set the server address and port [_socket connecttohost:@ "192.168.7.19" onport:6225 Error:nil]; }}//Authentication User-(Ibaction) Contentaction: (UIButton *) Sender {/* Key:value Dowhat:commit (authentication token) Username: _usernamefield.text ... * *//convert string to dictionary style wrapper send NSString *datastr= [NSString stringwith format:@ "{\" dowhat\ ": \" commit\ ", \" username\ ": \"%@\ ", \" password\ ": \"%@\ "}", _usernamefield.text,_pwdfield.text]; NSData *data=[datastr datausingencoding:nsutf8stringencoding]; /* Data sent to the server-1 request time-out-1 to wait for the server to reply tag is to match the method that originated the call in the callback method, not in the transmission data */[_socket Writedata:dat A withtimeout:-1 tag:0]; Listen for request message [_socket readdatawithtimeout:-1 tag:0]; The server returns a validation message _block=^ (BOOL result) {if (!result) {[email protected] ""; [email protected] ""; }else {//successful----record User name username=_usernamefield.text; _contbgview.hidden=yes; Login page Hide//Message page display _tableview.hidden=no; _sendview.hidden=no; } }; }//Registered User-(ibaction) Registeraction: (UIButton *) Sender {//Register page Controller Registerviewcontroller *ctrl=[[registerviewcont Roller alloc] init]; [Self Presentviewcontroller:ctrl animated:yes completion:^{; }]; Block callback (get registration page, username, password) ctrl.myblock=^ (nsstring *textnum,nsstring *textpassword) {//Resiger-Registration tag NSString *datastr= [NSString stringwithformat:@ "{\" dowhat\ ": \" Resiger\ ", \" username\ ": \"%@\ ", \" password\ ": \"%@\ "}" , Textnum,textpassword]; NSData *data=[datastr datausingencoding:nsutf8stringencoding]; Send a registration request to the server and listen for request information [_socket writedata:data withtimeout:-1 tag:0]; [_socket readdatawithtimeout:-1 tag:0]; }; }//send Message to Server-(ibaction) SendMessage: (UIButton *) Sender {if (_message.text.length >0) {//DisplayMessages in this client UI Nsdictionary *dic=[nsdictionary dictionary]; [Email protected] {@ "socket": @ "Client" @ "username": Username, @ "message": _message.text }; [Dataarr Addobject:dic]; Insert data into the last cell Nsindexpath *index=[nsindexpath indexpathforrow:dataarr.count-1 insection:0]; [_tableview Insertrowsatindexpaths:@[index] withrowanimation:uitableviewrowanimationfade]; Scroll to the last cell [_tableview scrolltorowatindexpath:index atscrollposition:uitableviewscrollpositionbottom Animated:YE S]; /* (content includes: Content tag, this client user name, whether the client, send content) of course, you can customize, as long as the server side also do the corresponding receive can */NSString *message= [nsstr ing stringwithformat:@ "{\" dowhat\ ": \" message\ ", \" username\ ": \"%@\ ", \" socket\ ": \" client\ ", \" message\ ": \"%@\ "}", Username,_message.text]; NSData *data=[message datausingencoding:nsutf8stringencoding]; Send a chat message to the server [_socket writedata:data withtimeout:-1 tag:0]; [_socket readdatawithtimeout:-1 tag:0]; [email protected] ""; }} #pragma mark-uitableview DataSource delegate-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection :(Nsinteger) section{return dataarr.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{static NSString *intenty = @ "UITableViewCell"; Mycell*cell = [TableView dequeuereusablecellwithidentifier:intenty]; if (cell = = nil) {Cell=[[[nsbundle mainbundle] loadnibnamed:@ "MyCell" owner:self Options:nil] lastobject]; } nsdictionary *message =dataarr[indexpath.row]; Give the model to the view to show Cell.message=message; return cell;} #pragma mark-asyncsocketdelegate//1. Protocol method called by client Connection server-(void) Onsocket: (Asyncsocket *) sock didconnecttohost: (nsstring *) host Port: (UInt16) port{//Listener server socket message [sock readdatawithtimeout:-1 tag:0]; }//2. Accept the data sent by the server (read data)-(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSDATA *) Data Withtag: (long) tag{//The server processes the message sent by the client, corresponding to the message that the client can identify (for example, the client sends a dictionary message to the server, and the server returns the corresponding dictionary message) Nsdictionary *dic=[n Sjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:nil];//NSLog (@ "%@", DIC); NSString *dowhat=[dic objectforkey:@ "Dowhat"]; Content tag NSString *type=[dic objectforkey:@ "type"]; Processing result if ([Dowhat isequaltostring:@ "commit"])//login validation return message {if ([type integervalue]==1) {Nslo G (@ "verify success"); _block (YES); }else {NSLog (@ "Verification failed"); }}else if ([Dowhat isequaltostring:@ "Resiger"])//Register return message {if ([type integervalue]==2) { NSLog (@ "registered successfully"); }else {}}else if ([dowhat isequaltostring:@ "message"])//Chat message return message {//Get other customer NSString *message=[dic objectforkey:@ "message"]; NSString *fromusername=[dic objectforkey:@ "username"];//nsstring *socket=[dic Objectforkey:@ "Socket"]; [Email protected] {@ "socket": @ "Server" @ "username": fromusername, @ "message": Message}; [Dataarr Addobject:dic]; The UI action is placed on the main thread Dispatch_async (Dispatch_get_main_queue (), ^{//inserting data into the last cell Nsindexpath *index=[ Nsindexpath indexpathforrow:dataarr.count-1 insection:0]; [_tableview Insertrowsatindexpaths:@[index] withrowanimation:uitableviewrowanimationfade]; Scroll to the last cell [_tableview scrolltorowatindexpath:index atscrollposition:uitableviewscrollpositionbottom Animated : YES]; }); }//Continue to listen for messages sent from the server [sock readdatawithtimeout:-1 tag:0];} @end
Registration page Remember to use block callbacks when the view returns to the landing page
Call--First Judge if (self.myblock! = nil) { self.myblock (_fieldnum.text,_fieldpassword.text); }
The layout sub-view needs to determine if the message is sending itself if ([What isequaltostring:@ "Client"]) { _iconimage.frame = CGRectMake (Kw-50, 10, 40, 40); C7/>_bgimage.frame = CGRectMake (kw-50-(size.width + -10), Size.width + +, Size.Height +); _conttext.frame = CGRectMake (kw-50-size.width-30, Size.width, size.height); _usernamelabel.frame=cgrectmake (Kw-70, 1, +); } else if ([What isequaltostring:@ "Server"]) { _iconimage.frame = CGRectMake (ten, ten, +, +); _bgimage.frame = CGRectMake (max, size.width + +, Size.Height +); _conttext.frame = CGRectMake (+, size.width, size.height); _usernamelabel.frame=cgrectmake (1, +); }
The cell layout determines how the layout is based on the source of the message in the dictionary.
The socket client is introduced here.
Instant Messaging: Socket usage