• 使用异步套接字客户端代码


    //

    //  ViewController.m

    //  异步套接字

    //

    //  Created by wyzc on 15-3-23.

    //  Copyright (c) 2015年 wyzc. All rights reserved.

    //

    #import "ViewController.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

    }

    - (void)didReceiveMemoryWarning {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

    - (IBAction)connBtn:(UIButton *)sender {

        self.socket=[[AsyncSocket alloc]initWithDelegate:self];

        NSError * err;

        if([self.socket connectToHost:@"127.0.0.1" onPort:90000 error:&err]==NO)

        {

            NSLog(@"%@",[err description]);

        }

    }

    - (IBAction)sendBtn:(UIButton *)sender {

        NSString * str=self.sendText.text;

        str=[str stringByAppendingString:@" "];

        [self.socket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];

    }

    - (IBAction)closeBtn:(UIButton *)sender {

        [self.socket disconnect];

        sender.enabled=NO;

        self.conn.enabled=YES;

    }

    //连接服务器成功

    -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port

    {

        NSLog(@"connection success!");

        self.conn.enabled=NO;

        self.close.enabled=YES;

        //准备接收或写数据

        [self.socket readDataWithTimeout:-1 tag:0];

    }

    //断开连接成功

    -(void)onSocketDidDisconnect:(AsyncSocket *)sock

    {

        NSLog(@"disconnection!");

        self.conn.enabled=YES;

        self.close.enabled=NO;

    }

    //错误断开连接

    -(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err

    {

        NSLog(@"error disconnection!");

        self.conn.enabled=YES;

        self.close.enabled=NO;

    }

    //接收数据

    -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

    {

        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

        self.revText.text=[NSString stringWithFormat:@"%@%@",self.revText.text,[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]];

        //准备继续接收或发送数据

        [self.socket readDataWithTimeout:-1 tag:0];

    }

    @end

  • 相关阅读:
    Day 13 匿名函数 :内置函数: 闭包
    Day 12 生成器:生成器表达式:列表表达式:yield:yield from:内置函数
    最近这些天
    正则表达式 I
    Python 软件规范开发
    模块
    常用模块介绍 time datetime os sys hashlib json pickle collections
    模拟博客园登录 基础版
    SQL 必知必会
    Python中的线程和进程
  • 原文地址:https://www.cnblogs.com/zkzzkz/p/5200916.html
Copyright © 2020-2023  润新知