ios socket编程的客户端和服务器端通信简单实例

服务器端代码

                #include <CoreServices/CoreServices.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 9000

void AcceptCallBack (CFSocketRef,CFSocketCallBackType,CFDataRef,const void *,void *);
void WriteStreamClientCallBack(CFWriteStreamRef stream,CFStreamEventType eventtype,void *);
void ReadStreamClientCallBack(CFReadStreamRef stream,CFStreamEventType eventtype,void *);


int main(int argc, const char * argv[])
{
    
    CFSocketRef sserver;
    CFSocketContext CTX = {0,NULL,NULL,NULL,NULL};
    sserver = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)AcceptCallBack, &CTX);
    if(sserver == NULL)
    {
        return -1;
    }
    int yes =1;
    setsockopt(CFSocketGetNative(sserver), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
    
    
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_len = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    
    CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr, sizeof(addr));
    if(CFSocketSetAddress(sserver, (CFDataRef)address) != kCFSocketSuccess)
    {
        fprintf(stderr, "socket 绑定失败\n");
        CFRelease(sserver);
        return -1;
    }
    
    CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, sserver, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes);
    CFRelease(sourceRef);
    printf("socket listening on port %d\n",PORT);
    CFRunLoopRun();
    
    
    return 0;
}
void AcceptCallBack (CFSocketRef socket,CFSocketCallBackType type,CFDataRef address,const void *data,void * info)
{
    CFReadStreamRef readstream = NULL;
    CFWriteStreamRef writestream = NULL;
    
    CFSocketNativeHandle sock = *(CFSocketNativeHandle *) data;
    CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock, &readstream, &writestream);
    if(!readstream || !writestream)
    {
        close(sock);
        fprintf(stderr, "cfstreamCreatpariWithsocket()失败\n");
        return;
    }
    
    CFStreamClientContext streamcontext = {0,NULL,NULL,NULL,NULL,};
    
    CFReadStreamSetClient(readstream, kCFStreamEventHasBytesAvailable, ReadStreamClientCallBack,&streamcontext);
    CFWriteStreamSetClient(writestream, kCFStreamEventCanAcceptBytes, WriteStreamClientCallBack, &streamcontext);
    
    CFReadStreamScheduleWithRunLoop(readstream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    CFWriteStreamScheduleWithRunLoop(writestream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    CFReadStreamOpen(readstream);
    CFWriteStreamOpen(writestream);
    
}
void WriteStreamClientCallBack(CFWriteStreamRef stream,CFStreamEventType eventtype,void * clientCallbackInfo)
{
    UInt8 buff[] = "hello client";
    CFWriteStreamRef writestream = stream;
//    if(NULL !=writestream)
//    {
//        CFWriteStreamWrite(stream, buff, 255);
//        printf("接收到数据:%s\n",buff);
//        CFWriteStreamClose(writestream);
//        CFWriteStreamUnscheduleFromRunLoop(writestream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
//        writestream = NULL;
//    }
    
    if(NULL != writestream)
    {
        CFWriteStreamWrite(writestream, buff, strlen((const char *)buff)+1);
        CFWriteStreamClose(writestream);
        CFWriteStreamUnscheduleFromRunLoop(writestream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
        writestream = NULL;
    }
}
void ReadStreamClientCallBack(CFReadStreamRef stream,CFStreamEventType eventtype,void * clientcallBackInfo)
{
    UInt8 buff[255];
    CFReadStreamRef inputstream = stream;
    if(NULL !=inputstream)
    {
        CFReadStreamRead(stream, buff, 255);
        printf("接收到数据:%s\n",buff);
        CFReadStreamClose(inputstream);
        CFReadStreamUnscheduleFromRunLoop(inputstream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
        inputstream = NULL;
    }

}








客户端代码:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
   
    m_button1 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];
    m_button2 = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 200, 40)];
    [m_button1 setTitle:@"发送" forState:UIControlStateNormal];
    [m_button2 setTitle:@"接收" forState:UIControlStateNormal];
    [m_button1 setBackgroundColor:[UIColor blueColor]];
    [m_button2 setBackgroundColor:[UIColor blueColor]];
    [m_button1 addTarget:self action:@selector(button1click) forControlEvents:UIControlEventTouchDown];
    [m_button2 addTarget:self  action:@selector(button2click) forControlEvents:UIControlEventTouchDown];
    
    m_labell = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 200, 40)];
    
    
    [self.window addSubview:m_button2];
    [self.window addSubview:m_button1];
    [self.window addSubview:m_labell];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)button1click
{
    flag = 0;
    [self initwithnetwork];
}

-(void)button2click
{
    flag = 1;
    [self initwithnetwork];
}

-(void)initwithnetwork
{
    CFReadStreamRef readstream;
    CFWriteStreamRef writestream;

    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"10.20.53.35", PORT, &readstream, &writestream);

    _outputStream = (__bridge_transfer NSOutputStream *)writestream;
    inputStream = (__bridge_transfer NSInputStream *)readstream;
   
    [inputStream setDelegate:self];
    [_outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [_outputStream open];
}

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    NSString *event;
    switch (eventCode) {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            

            break;
        case NSStreamEventHasBytesAvailable:
            event = @"NSStreamEventHasBytesAvailable";
            if(flag == 1&& aStream == inputStream)
            {
                NSMutableData *input = [[NSMutableData alloc]init];
                UInt8 buffer[1024];
                int len;
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if(len>0)
                    {
                        [input appendBytes:buffer length:len];
                    }
                }
                
                NSString *resultstring = [[NSString alloc]initWithData:input encoding:NSUTF8StringEncoding];
                NSLog(@"接收:%@",resultstring);
                m_labell.text = resultstring;
            }

                        break;
            
        case NSStreamEventHasSpaceAvailable:
            event = @"NSStreamEventHasSpaceAvailable";
            if(flag == 0&& aStream == _outputStream)
            {
               
                UInt8 buffer[] = "hello server";
                [_outputStream write:buffer maxLength:strlen((const char *)buffer)+1];
                [_outputStream close];
                
            }
            

            break;
            
            case NSStreamEventErrorOccurred:
            event = @"NSStreamEventErrorOccurred";
            m_labell.text =event;
        default:
            
            break;
    }
}


实例图如上...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值