以下是代码
#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interfaceViewController ()<GCDAsyncSocketDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
- (IBAction)connectToSocket:(id)sender;
- (IBAction)loginToSocket:(id)sender;
@property (weak, nonatomic) IBOutletUITableView *tableView;
@property (strong,nonatomic) GCDAsyncSocket *socket;
@property (weak, nonatomic) IBOutletNSLayoutConstraint *bottomHight;
@property (strong, nonatomic) NSMutableArray *message;
@end
@implementation ViewController
-(NSMutableArray *)message{
if (_message == nil) {
_message = [NSMutableArrayarray];
}
return_message;
}
- (void)viewDidLoad {
[superviewDidLoad];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyWillShow:) name:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyWillDisappear:) name:UIKeyboardWillHideNotificationobject:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - 键盘弹起
- (void)keyWillShow:(NSNotification *)noti{
NSLog(@"%@",noti.userInfo);
CGFloat hight = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
self.bottomHight.constant = hight ;
}
#pragma mark - 键盘退回
- (void)keyWillDisappear:(NSNotification *)noti{
self.bottomHight.constant = 0;
}
- (IBAction)connectToSocket:(id)sender {
NSString *host = @"127.0.0.1";
int port = 12345;
self.socket = [[GCDAsyncSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(0, 0)];
NSError *error = nil;
[self.socketconnectToHost:host onPort:port error:&error];
if (error) {
NSLog(@"connectToHost:%@",error);
}
}
- (IBAction)loginToSocket:(id)sender {
NSString *loginStr = @"iam:zhangsan";
[self.socketwriteData:[loginStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1tag:101];
}
#pragma mark -SocketDelegate
#pragma mark -连接成功
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
NSLog(@"%s",__func__);
}
#pragma mark -连接失败
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
if (err) {
NSLog(@"连接失败 ");
}else{
NSLog(@"正常断开");
}
}
#pragma mark -发送数据
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"发送成功%s",__func__);
[sock readDataWithTimeout:-1tag:tag];
}
#pragma mark -读取数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSLog(@"%s",__func__);
if (tag ==102) {
NSString *receiver = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
[self.messageaddObject:receiver];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableViewreloadData];
});
NSLog(@"%@",receiver);
}
}
#pragma mark -tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
returnself.message.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
staticNSString *ID = @"SocketCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
cell.textLabel.text = self.message[indexPath.row];
return cell;
}
#pragma mark - socrollDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self.viewendEditing:YES];
}
#pragma mark -textFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
NSString *txt = textField.text;
if (txt.length ==0) {
returnYES;
}
NSString *msg = [@"msg:"stringByAppendingString:txt];
[self.socketwriteData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1tag:102];
returnYES;
}
- (void)dealloc{
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
@end