Socket Communication (i)

Source: Internet
Author: User

////VIEWCONTROLLER.M//Socket1////Created by Arenoba on 16/5/7.//copyright©2016 year aren. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller () <nsstreamdelegate, Uitextfielddelegate, Uitableviewdatasource, uitableviewdelegate>{Nsinputstream*_inputstream; Nsoutputstream*_outstream;}//@property (Weak, nonatomic) Iboutlet nslayoutconstraint *bottomviewconstraint;@property (Weak, nonatomic) Iboutlet UIView *commentview;//The parent view of the text box that sends the message, setting its frame depending on whether the keyboard appears or not@property (Weak, nonatomic) iboutlet UITableView *TableView, @property (nonatomic, strong) Nsmutablearray*CHATMSGS;//Chat Message Array@end@implementationViewcontroller-(Nsmutablearray *) chatmsgs{if(!_chatmsgs) {_chatmsgs=[Nsmutablearray array]; }    return_chatmsgs;}//button to connect to the server-(Ibaction) Connect: (ID) sender{//1. Get the IP address and port number of the serverNSString *host =@"127.0.0.1"; intPort =8080; //2. Get the input and output streamCfreadstreamref Readref;        Cfwritestreamref Writeref; //3. Convert C-Language objects to OC objects_inputstream = (__bridge Nsinputstream *) (READREF); _outstream= (__bridge Nsoutputstream *) (WRITEREF); //4. Establish a connectionCfstreamcreatepairwithsockettohost (NULL, __bridge cfstringref) host, Port, &readref, &writeref); //5. Setting up the agent_inputstream.Delegate=Self ; _outstream.Delegate=Self ;#pragmaMark---If you do not add to the main loop, the proxy method may not execute----//6. Throw into the main loop[_inputstream scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];        [_outstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; //7. Open the input/output stream[_inputstream Open]; [_outstream Open];#pragmaMark---The end of the link, you need to remove the input and output stream from the main loop and close the input and output stream, executing in the proxy method----    }//Login Button-(ibaction) Login: (ID) sender{//command to log inNSString *loginstring =@"Iam:arenouba"; //convert to NSData typeNSData *data =[loginstring datausingencoding:nsutf8stringencoding]; //The output stream sends the login data to the server[_outstream write:data.bytes maxLength:data.length]; }#pragmaMark---Input stream read the data returned by the server XMPP is already encapsulated, so we don't have to deal with----(void) readdata{//create a buffer that can put 1024 bytesuint8_t buf[1024x768]; //Len Returns the number of bytes actually storedNsinteger len = [_inputstream read:buf maxLength:sizeof(BUF)];//sizeof (BUF)//Convert bytes to stringsNSData *data =[NSData datawithbytes:buf Length:len]; //convert data received from the server to a stringNSString *recievestring =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; //Refresh Data[self reloaddatawithtext:recievestring]; NSLog (@"%@", recievestring);}#pragmaMark---Click the Send button to get the text of the input box and refresh TableView----(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{NSString*text =Textfield.text; NSData*data =[text datausingencoding:nsutf8stringencoding];    [Self reloaddatawithtext:text]; //sending data to the server[_outstream write:data.bytes maxLength:data.length]; //Empty text box when send is completeTextfield.text =Nil; returnYES;}- (void) Reloaddatawithtext: (NSString *) text{//add data from the text input box to the message array[Self.chatmsgs Addobject:text]; //Refresh[Self.tableview Reloaddata]; //send a message so that TableView scrolls up one lineNsindexpath *lastindexpath = [Nsindexpath indexPathForRow:self.chatMsgs.count-1Insection:0]; [Self.tableview scrolltorowatindexpath:lastindexpath Atscrollposition:uitableviewscrollpositionbottom Animated:    YES]; }#pragmaWhen Mark---is about to drag, the keyboard disappears----(void) Scrollviewwillbegindragging: (Uiscrollview *) scrollview{[Self.view endediting:yes];}#pragmaMark----nsstreamdelegate------(void) Stream: (Nsstream *) Astream handleevent: (nsstreamevent) eventcode{#warningMark---This is done in the main thread.NSLog (@"%@", [Nsthread CurrentThread]); /*nsstreameventnone = 0, nsstreameventopencompleted = 1UL << 0, input output stream open complete Nsstreameventhasbytesavaila ble = 1UL << 1, byte readable nsstreameventhasspaceavailable = 1UL << 2, can send byte nsstreameventerroroccurred = 1 UL << 3, connection error nsstreameventendencountered = 1UL << 4 end of connection*/        Switch(EventCode) { CaseNsstreameventopencompleted:nslog (@"input/output stream open complete");  Break;  CaseNsstreameventhasbytesavailable:nslog (@"byte-readable");  Break;  CaseNsstreameventhasspaceavailable:nslog (@"can send bytes");  Break;  CaseNsstreameventerroroccurred:nslog (@"Connection Error");  Break;  CaseNsstreameventendencountered:nslog (@"End of Connection"); //turn off the input and output stream[_inputstream Close];                        [_outstream Close]; //removing from the main loop[_inputstream removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];                        [_outstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];  Break; default:             Break; }    }- (void) viewdidload {[Super viewdidload]; //when the listening keyboard is going to appear[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (Keyboardwillchang:) Name: UikeyboardwillchangeframenotificationObject: nil]; //when the listening keyboard is going to be hidden[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (keyboardwillhidden:) Name: UikeyboardwillhidenotificationObject: nil]; Self.tableview.Delegate=Self ; Self.tableView.dataSource=Self ; [Self.view insertsubview:_tableview Atindex:0]; //additional setup after loading the view, typically from a nib.}- (void) Keyboardwillchang: (Nsnotification *) noti{NSLog (@"%@", Noti.userinfo); //the Y value of the keyboard endCGRect Kbendframe =[Noti.userinfo[uikeyboardframeenduserinfokey] cgrectvalue]; [UIView Animatewithduration:[noti.userinfo[uikeyboardanimationdurationuserinfokey] floatvalue] Animations:^{self.commentView.transform= Cgaffinetransformmaketranslation (0, -kbEndFrame.size.height); }];}- (void) Keyboardwillhidden: (Nsnotification *) noti{//the Y value of the keyboard end[UIView Animatewithduration:[noti.userinfo[uikeyboardanimationdurationuserinfokey] Floatvalue] animations:^{self.commentView.transform=cgaffinetransformidentity; }];}-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{returnSelf.chatMsgs.count;}-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{StaticNSString *id =@"Cell"; UITableViewCell*cell =[TableView Dequeuereusablecellwithidentifier:id];

If (cell = = Nil) {

cell = [[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier: ID];

}


Cell.textLabel.text = Self.chatmsgs[indexpath.row]; return cell;} -(void) didreceivememorywarning { [super didreceivememorywarning]; // Dispose of any resources the can be recreated. }@end

Socket Communication (i)

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.