iOS 基于Socket TCP/IP通讯

  //服务器端代码
  self.navigationItem.title = @"接受消息";
    [self createTcpSocket];
    // 默认端口号
    _duankou.text = @"12345";
    
    //搭建聊天的页面
    testV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-50, 320, 50)];
    //打开交互
    testV.userInteractionEnabled = YES;
//    testV.backgroundColor = [UIColor yellowColor];
//    testV.backgroundColor = [UIColor grayColor];
    
    //搞个UITextView
    textField  = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 230, 40)];
    textField.delegate = self;
    textField.placeholder = @"请输入内容";
    textField.borderStyle = UITextBorderStyleRoundedRect;
    
    //搞个发送消息的按钮
    UIButton *sendMg = [UIButton buttonWithType:UIButtonTypeCustom];
    [sendMg setTitle:@"Send" forState:UIControlStateNormal];
    [sendMg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendMg addTarget:self action:@selector(sendMG) forControlEvents:UIControlEventTouchUpInside];
    [sendMg setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    sendMg.frame = CGRectMake(250, 5, 60, 40);
    [testV addSubview:sendMg];
    [testV addSubview:textField];
    [self.view addSubview:testV];
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
    [self addText:[NSString stringWithFormat:@"建立与%@的连接",newSocket.connectedHost]];
    
    socket = newSocket;
    socket.delegate = self;
    [socket readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *receive = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self addText:[NSString stringWithFormat:@"%@:%@",sock.connectedHost,receive]];
    NSString *reply = [NSString stringWithFormat:@"收到:%@",receive];
    [socket writeData:[reply dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    
 
    
    [socket readDataWithTimeout:-1 tag:0];
}
- (void)createTcpSocket {
 
//    dispatch_queue_t dQueue = dispatch_queue_create(@"My socket queue", NULL);
}
//消息显示换行
- (void)addText:(NSString *)str {
    _showMg.text = [_showMg.text stringByAppendingFormat:@"%@\n",str];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//监听
- (IBAction)connectBT:(id)sender {
    NSLog(@"listen");
    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *err = nil;
    if (![socket acceptOnPort:[_duankou.text intValue] error:&err]) {
        [self addText:err.description];
    } else {
        [self addText:[NSString stringWithFormat:@"开始监听%ld端口",_duankou.text.integerValue]];
    }
}
//连接到的地方
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    [self addText:[NSString stringWithFormat:@""]];
    [socket readDataWithTimeout:-1 tag:0];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
}
//发送消息
- (void)sendMG {
    //做动画过度
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    testV.frame = CGRectMake(0, self.view.bounds.size.height - 50, 375, 50);
    [UIView commitAnimations];
    [textField resignFirstResponder];
  
    
   [socket writeData:[textField.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    [self addText:[NSString stringWithFormat:@"我:%@",textField.text]];
    [textField resignFirstResponder];
    [socket readDataWithTimeout:-1 tag:0];
    
    //客户端代码
     //注册键盘通知让消息框弹起
    [self  registerForKeyboardNotifications];
    
    //搭建聊天界面
    testV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50, 320, 50)];
    testV.userInteractionEnabled = YES;

    textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 230, 40)];
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    
    //发送消息按钮
    UIButton *sendMg = [UIButton buttonWithType:UIButtonTypeCustom];
    [sendMg setTitle:@"Send" forState:UIControlStateNormal];
    [sendMg setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    [sendMg addTarget:self action:@selector(sendMG) forControlEvents:UIControlEventTouchUpInside];
    [sendMg setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    sendMg.frame = CGRectMake(250, 5, 60, 40);
    [testV addSubview:sendMg];
    [testV addSubview:textField];
    [self.view addSubview:testV];
}

//注册键盘弹起来的通知
- (void)registerForKeyboardNotifications {
    //监听键盘
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContentViewPotin:) name:UIKeyboardWillShowNotification object:nil];
    //监听键盘改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];
    
}

//通知键盘移动
- (void)changeContentViewPoint:(NSNotification *)sender {
    NSDictionary *userInfo = sender.userInfo;
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyBoardEndY = value.CGRectValue.origin.y;
    //得到键盘弹起后的键盘视图所在y坐标
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    //添加移动动画,使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        testV.center = CGPointMake(testV.center.x, keyBoardEndY - testV.bounds.size.height / 2);
    }];
}

// 收起键盘
- (void)dsms {
    [textField resignFirstResponder];
    [_duankou resignFirstResponder];
    [_IP resignFirstResponder];
    //做动画过度
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    testV.frame = CGRectMake(0, self.view.bounds.size.height - 50, 320, 50);
    [UIView commitAnimations];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//将消息显示换行
-(void)addText:(NSString *)str
{
    _showMg.text = [_showMg.text stringByAppendingFormat:@"%@\n",str];
}
//连接服务器
- (IBAction)connect:(id)sender {
    socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    //socket.delegate = self;
    NSError *err = nil;
    if(![socket connectToHost:_IP.text onPort:[_duankou.text intValue] error:&err])
    {
        [self addText:err.description];
    }else
    {
        NSLog(@"ok");
        [self addText:@"打开端口"];
    }
    
    [self dsms];
}

//连接到地方
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    [self addText:[NSString stringWithFormat:@"连接到:%@",host]];
    [socket readDataWithTimeout:-1 tag:0];
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
//    NSString *newMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
   [self addText:[NSString stringWithFormat:@"服务器%@: %@",sock.connectedHost,newMessage]];
    
    [socket readDataWithTimeout:-1 tag:0];
}

//发送消息
- (void)sendMG{
    //做动画过渡
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    testV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);
    [UIView commitAnimations];
    
  
    
    textField.text = [NSString stringWithFormat:@"%@",data];
    NSLog(@"$$$$%@",textField.text);
//    
    [socket writeData:[textField.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    
    [self addText:[NSString stringWithFormat:@"我:%@",textField.text]];
    [textField resignFirstResponder];
    [socket readDataWithTimeout:-1 tag:0];
}
}


你可能感兴趣的:(ios开发)