---restore content starts---
#import "ViewController.h" @interface Viewcontroller () <nsstreamdelegate,uitextfielddelegate, uitableviewdatasource,uitableviewdelegate>{nsinputstream *_inputstream;//corresponding input stream NSOutputStream *_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@implementation viewcontroller-(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/Receive data//monitor keyboard [[Nsnotificationcenter Defaultcenter] addobserver:self s Elector: @selector (kbfrmwillchange:) name:uikeyboardwillchangeframenotification Object:nil];} -(void) Kbfrmwillchange: (nsnotification *) noti{NSLog (@ "%@", Noti.userinfo); Gets the height of the window cgfloat windowh = [UIScreen mainscreen].bounds.size.height; Keyboard end of frm cgrect kbendfrm = [Noti.userinfo[uikeyboardframeenduserinfokey] cgrectvalue]; Gets the Y value of the end of the keyboard cgfloat kbendy = KBENDFRM.ORIGIN.Y; Self.inputViewConstraint.constant = Windowh-kbendy;} -(void) stream: (Nsstream *) Astream handleevent: (nsstreamevent) eventcode{NSLog (@ "%@", [Nsthread CurrentThread]);//NS streameventopencompleted = 1UL << 0,//input/output stream open complete//nsstreameventhasbytesavailable = 1UL << 1,//byte-readable/NS streameventhasspaceavailable = 1UL << 2,//can issue bytes//nsstreameventerroroccurred = 1UL << 3,//connection error//NSS treameventendencountered = 1UL << 4//connection End switch (eventcode) {case nsstreameventopencompleted: NSLog (@ "input/output stream open complete"); Break Case Nsstreameventhasbytesavailable:nslog (@ "byte-readable"); [Self readdata]; Break Case NsstreameventhasspaceavailaBle:nslog (@ "can send bytes"); Break Case Nsstreameventerroroccurred:nslog (@ "connection error"); Break Case Nsstreameventendencountered:nslog (@ "Connection end"); Close the input and output stream [_inputstream close]; [_outputstream Close]; Remove [_inputstream removefromrunloop:[nsrunloop Mainrunloop] Formode:nsdefaultrunloopmode] from the main run cycle; [_outputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; Break Default:break; }}-(Ibaction) Connecttohost: (ID) Sender {//1. To establish a connection nsstring *host = @ "127.0.0.1"; int port = 12345; Define C language input and output stream cfreadstreamref 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 proxy _inputstream.delegate = self; _outputstream.delegate = self; Adding an input/output stream to the main run loop//not adding the main run Loop agent may not work [_inputstream Scheduleinrunloop:[nsrunloop Mainrunloop] Formode:nsdefaultrunl Oopmode]; [_outputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; Open input/output stream [_inputstream open]; [_outputstream open];} -(Ibaction) Loginbtnclick: (ID) Sender {//Login//Send username and password//when doing this, only the user name, password will not be sent//if you want to log in, send the data format is "I Am:zhangsan "; If you want to send a chat message, the data format is "Msg:did you have dinner"; Login instructions NSString *loginstr = @ "Iam:zhangsan"; Turn str into nsdata nsdata *data = [Loginstr datausingencoding:nsutf8stringencoding]; [_outputstream write:data.bytes maxLength:data.length];} #pragma mark reads the data returned by the server-(void) readdata{//Create a buffer that can put 1024 bytes uint8_t buf[1024]; Returns the number of bytes actually loaded nsinteger len = [_inputstream Read:buF maxlength:sizeof (BUF)]; Converts a byte array into a string nsdata *data = [NSData datawithbytes:buf Length:len]; Data received from the server nsstring *recstr = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@ "%@", recstr); [Self reloaddatawithtext:recstr]; }-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{nsstring *text = Textfield.text; NSLog (@ "%@", text); Chat information NSString *msgstr = [NSString stringwithformat:@ "msg:%@", text]; Turn str into nsdata nsdata *data = [MsgStr datausingencoding:nsutf8stringencoding]; Refresh table [self reloaddatawithtext:msgstr]; Send data [_outputstream write:data.bytes maxLength:data.length]; After sending the data, empty textField Textfield.text = nil; return YES;} -(void) Reloaddatawithtext: (NSString *) text{[self.chatmsgs Addobject:text]; [Self.tableview Reloaddata]; Data many, should scroll upward nsindexpath *lastpath = [Nsindexpath indexpathforrow:self.chatmsgs.count-1 insection:0]; [Self.tableview Scrolltorowatindexpath:lastpath atscrollposition:uitableviewscrollpositionbottom Animated:YES];} Data source for #pragma mark table-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{return Self.chatMsgs.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{static NSString *id = @ "Cell"; UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id]; Cell.textLabel.text = Self.chatmsgs[indexpath.row]; return cell;} -(void) scrollviewwillbegindragging: (Uiscrollview *) scrollview{[Self.view Endediting:yes];} @end
PS: Note:
1. If you need to connect to the server
2. Input and output streams need to be added to the main run loop
3. Input stream: Used to write data
4. Output stream: Used to read data
Summary of steps:
1. Establish the connection, set the IP and port number
2. Through the establishment of the C language input and output stream, connect the server, and then convert the input and output of the C language into OC object
3. Set the input and output stream agent for the OC type to the current controller
4. Add the input and output stream to the main run loop to open the input/output stream
5. Client sends data to the server (output stream)
6. The server returns data to the client (input stream)
7. Current controller refreshes the main interface data
---restore content ends---
Simple chat room for iOS instant Messaging