首页 > 其他 > 详细

iOS开发-AsynSocket

时间:2014-01-21 09:59:51      阅读:368      评论:0      收藏:0      [点我收藏+]

导入AsynSocket库,导入CFNetwork系统库

1.新建single view工程

ViewController.h文件

#import <UIKit/UIKit.h>
#import "AsyncSocket.h"

@interface ViewController : UIViewController <AsyncSocketDelegate> {
    NSMutableArray *_socketArray;
    AsyncSocket *_sendSocket;//发送
    AsyncSocket *_recvSocket;//接收
}
- (IBAction)sendClick:(id)sender;
@property (retain, nonatomic) IBOutlet UITextField *ipField;
@property (retain, nonatomic) IBOutlet UITextField *sendField;
@property (retain, nonatomic) IBOutlet UITextView *msgView;
- (IBAction)conClick:(id)sender;
- (IBAction)sendClick:(id)sender;
@end

2.ViewController.m文件

#import "ViewController.h"

@implementation ViewController
@synthesize ipField;
@synthesize sendField;
@synthesize msgView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    //初始化socket数组,存放socket
    _socketArray = [[NSMutableArray alloc] init];
    
    //实例化客户端和服务器socket
    _sendSocket = [[AsyncSocket alloc] initWithDelegate:self];
    _recvSocket = [[AsyncSocket alloc] initWithDelegate:self];
    
    //服务器段开始监听
    [_recvSocket acceptOnPort:5566 error:nil];
}

//服务器端接收到新的socket
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
    //服务器端将收到的socket存入数组
    [_socketArray addObject:newSocket];
    //开始接收数据
    [newSocket readDataWithTimeout:-1 tag:0];
}

//服务器端接收到信息
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    self.msgView.text = [NSString stringWithFormat:@"%@%@:%@\n", self.msgView.text, sock.connectedHost, string];
    [sock readDataWithTimeout:-1 tag:0];//循环
}

//连接
- (IBAction)conClick:(id)sender {
    if (_sendSocket.isConnected) {
        [_sendSocket disconnect];
    }
    [_sendSocket connectToHost:self.ipField.text onPort:5566 withTimeout:30 error:nil];
}

//发送消息
- (IBAction)sendClick:(id)sender {
    NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding];
    [_sendSocket writeData:data withTimeout:30 tag:0];
    self.sendField.text = @"";
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"连接服务器成功");
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"断开连接");
}



- (void)dealloc {
    [ipField release];
    [sendField release];
    [msgView release];
    [ipField release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setIpField:nil];
    [super viewDidUnload];
}
@end


iOS开发-AsynSocket

原文:http://blog.csdn.net/zwf_apple/article/details/18224673

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!