iOS 网络编程 GCDasynsocket socket 发送数据

来源:互联网 发布:绿化预算软件 编辑:程序博客网 时间:2024/05/17 00:58

//

//  ViewController.m

//  070604gcdasynsocket

//

//  Created by tianshangrenjian on 15/7/6.

//  Copyright © 2015 tianshangrenjian. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()<GCDAsyncSocketDelegate>

- (IBAction)btStart:(id)sender;

- (IBAction)sendMsg:(id)sender;

@property (strong ,nonatomic)GCDAsyncSocket *socket;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

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

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    NSLog(@"connect to server successful!");

    [self.socketreadDataWithTimeout:-1tag:1];

}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err

{

    NSLog(@"fuck errro :%@",err);

}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *str=[[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

   NSLog(@"%@",str);

}


- (IBAction)btStart:(id)sender {

    

    GCDAsyncSocket *socket=[[GCDAsyncSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)];

   NSString *host=@"127.0.0.1";

    [socket connectToHost:host onPort:12345 error:nil];

 //   socket.delegate=self;

   self.socket=socket;

}


- (IBAction)sendMsg:(id)sender {

    

    NSString *str=@"up:lsslksks";

    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

    [self.socket writeData:data withTimeout:-1 tag:1];

    

}






































@end


0 0
原创粉丝点击