IOS connection Server (socket)

Source: Internet
Author: User

////VIEWCONTROLLER.M//05. Chat Room////Created by Apple on 14/12/5.//Copyright (c) Heima. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller () <NSStreamDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>{Nsinputstream*_inputstream;//corresponding input streamNsoutputstream *_outputstream;//corresponding output stream} @property (weak, nonatomic) Iboutlet nslayoutconstraint*Inputviewconstraint, @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;}- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib. //2. Send and receive Data//Make a chat//1. User Login//2. Send and receive Data//Monitor Keyboard[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (kbfrmwillchange:) Name: UikeyboardwillchangeframenotificationObject: nil];}-(void) Kbfrmwillchange: (Nsnotification *) noti{NSLog (@"%@", Noti.userinfo); //gets the height of the windowcgfloat windowh=[UIScreen mainscreen].bounds.size.height; //keyboard end of frmCGRect kbendfrm =[Noti.userinfo[uikeyboardframeenduserinfokey] cgrectvalue]; //Gets the Y value of the keyboard endCGFloat Kbendy =KBENDFRM.ORIGIN.Y; Self.inputViewConstraint.constant= WINDOWH-Kbendy;}-(void) Stream: (Nsstream *) Astream handleevent: (nsstreamevent) eventcode{NSLog (@"%@", [Nsthread CurrentThread]);//nsstreameventopencompleted = 1UL << 0,//input/output stream open complete//nsstreameventhasbytesavailable = 1UL << 1,//byte-readable//nsstreameventhasspaceavailable = 1UL << 2,//can issue bytes//nsstreameventerroroccurred = 1UL << 3,//connection Error occurred//nsstreameventendencountered = 1UL << 4//End of Connection    Switch(EventCode) { CaseNsstreameventopencompleted:nslog (@"input/output stream open complete");  Break;  CaseNsstreameventhasbytesavailable:nslog (@"byte-readable");            [Self readdata];  Break;  CaseNsstreameventhasspaceavailable:nslog (@"can send bytes");  Break;  CaseNsstreameventerroroccurred:nslog (@"connection Error occurred");  Break;  CaseNsstreameventendencountered:nslog (@"End of Connection"); //turn off the input and output stream[_inputstream Close];                        [_outputstream Close]; //Remove from main run loop[_inputstream removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];            [_outputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];  Break; default:             Break; }    }-(Ibaction) Connecttohost: (ID) Sender {//1. Establish a connectionNSString *host =@"127.0.0.1"; intPort =12345; //defining C language input and output streamsCfreadstreamref Readstream;    Cfwritestreamref Writestream; Cfstreamcreatepairwithsockettohost (NULL, (__bridge cfstringref) host, Port,&readstream, &Writestream); //Convert c input and output stream to OC object_inputstream = (__bridge Nsinputstream *) (Readstream); _outputstream= (__bridge Nsoutputstream *) (Writestream); //Set up proxy_inputstream.Delegate=Self ; _outputstream.Delegate=Self ; //Add the input stream to the main run loop//do not add main run loop agent may not work[_inputstream scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];        [_outputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; //Open the input and output stream[_inputstream Open]; [_outputstream open];}-(Ibaction) Loginbtnclick: (ID) Sender {//Login//send user name and password//when doing this, only the user name, the password will not be sent//if you want to log in, send the data format as "Iam:zhangsan"; //If you want to send a chat message, the data format is "Msg:did you have dinner"; //sign-in instructionsNSString *loginstr =@"Iam:zhangsan"; //turn str into NSDataNSData *data =[Loginstr datausingencoding:nsutf8stringencoding]; [_outputstream write:data.bytes maxLength:data.length];}#pragmaMark reads the data returned by the server-(void) readdata{//set up a buffer to put 1024 bytesuint8_t buf[1024x768]; //returns the number of bytes actually loadedNsinteger len = [_inputstream read:buf maxLength:sizeof(BUF)]; //Convert a byte array to a stringNSData *data =[NSData datawithbytes:buf Length:len]; //data received from the serverNSString *recstr =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"%@", RECSTR);    [Self reloaddatawithtext:recstr]; }-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{NSString*text =Textfield.text; NSLog (@"%@", text); //Chat InformationNSString *msgstr = [NSString stringWithFormat:@"msg:%@", text]; //turn str into NSDataNSData *data =[MsgStr datausingencoding:nsutf8stringencoding]; //Refresh Table[self reloaddatawithtext:msgstr]; //Send Data[_outputstream write:data.bytes maxLength:data.length]; //send out data, empty TextFieldTextfield.text =Nil; returnYES;}-(void) Reloaddatawithtext: (NSString *) text{[Self.chatmsgs Addobject:text];        [Self.tableview Reloaddata]; //more data, should scroll upwardsNsindexpath *lastpath = [Nsindexpath indexPathForRow:self.chatMsgs.count-1Insection:0]; [Self.tableview Scrolltorowatindexpath:lastpath atscrollposition:uitableviewscrollpositionbottom Animated:YES];}#pragmaThe data source for the Mark table-(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]; Cell.textLabel.text=Self.chatmsgs[indexpath.row]; returncell;}-(void) Scrollviewwillbegindragging: (Uiscrollview *) scrollview{[Self.view endediting:yes];}@end

IOS connection Server (socket)

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.