码迷,mamicode.com
首页 > 移动开发 > 详细

iOS socket

时间:2014-08-14 14:01:18      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   使用   os   io   文件   

在CFSocket中,TCP连接的创建为

csocket = CFSocketCreate(

                                         kCFAllocatorDefault,

                                         PF_INET,

                                        SOCK_STREAM,

                                        IPPROTO_TCP,

                                         kCFSocketReadCallBack,

                                        TCPServerConnectCallBack,

                                        &ctx);

                                   。。。。

sError = CFSocketConnectToAddress(csocket,address, -1);

 

这里在连接成功时回调用TCPServerConnectCallBack方法,

那么如果需要UDP传输数据的话,

csocket = CFSocketCreate(

                                         kCFAllocatorDefault,

                                         PF_INET,

                                        SOCK_DGRAM,

                                         IPPROTO_UDP,

                                        kCFSocketConnectCallBack,

                                        TCPServerConnectCallBack,

                                        &ctx);

 

1.TCP是有连接的,可靠的、可控制的、无边界的socket通信。

2.UDP是无连接的、不可靠的 数据报通信。但是效率高。

 

所以在TCP中要用回调来确定是否连接成功,而原生的socket连接成功是通过serveice发回信息来确定。UDP无连接,所以不需要回调,而不管是否发送成功。

 

 

 

第三部分、完整的使用方法

 

客户端:

导入头文件:

#import <sys/socket.h>

#import <netinet/in.h>

#import <arpa/inet.h>

#import <unistd.h>

1. 创建连接

 

CFSocketContext sockContext = {0, // 结构体的版本,必须为0

self,

 

// 一个任意指针的数据,可以用在创建时CFSocket对象相关联。这个指针被传递给所有的上下文中定义的回调。

NULL, // 一个定义在上面指针中的retain的回调, 可以为NULL

NULL, NULL};

CFSocketRef _socket = (kCFAllocatorDefault,// 为新对象分配内存,可以为nil

PF_INET, // 协议族,如果为0或者负数,则默认为PF_INET

SOCK_STREAM, // 套接字类型,如果协议族为PF_INET,则它会默认为SOCK_STREAM

IPPROTO_TCP, // 套接字协议,如果协议族是PF_INET且协议是0或者负数,它会默认为IPPROTO_TCP

kCFSocketConnectCallBack, // 触发回调函数的socket消息类型,具体见CallbackTypes

TCPServerConnectCallBack, // 上面情况下触发的回调函数

&sockContext // 一个持有CFSocket结构信息的对象,可以为nil

);

 

 

if (_socket != nil) {

   struct sockaddr_in addr4;   //IPV4

   memset(&addr4, 0, sizeof(addr4));

   addr4.sin_len = sizeof(addr4);

   addr4.sin_family = AF_INET;

   addr4.sin_port = htons(8888);

   addr4.sin_addr.s_addr = inet_addr([strAddress UTF8String]);  // 把字符串的地址转换为机器可识别的网络地址

      

   // 把sockaddr_in结构体中的地址转换为Data

   CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8*)&addr4, sizeof(addr4));

   CFSocketConnectToAddress(_socket, // 连接的socket

address, // CFDataRef类型的包含上面socket的远程地址的对象

-1 // 连接超时时间,如果为负,则不尝试连接,而是把连接放在后台进行,如果_socket消息类型为kCFSocketConnectCallBack,将会在连接成功或失败的时候在后台触发回调函数

);

   CFRunLoopRef cRunRef = CFRunLoopGetCurrent();    // 获取当前线程的循环

   // 创建一个循环,但并没有真正加如到循环中,需要调用CFRunLoopAddSource

   CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault,_socket, 0);

   CFRunLoopAddSource(cRunRef, // 运行循环

   sourceRef,  // 增加的运行循环源, 它会被retain一次

   kCFRunLoopCommonModes  // 增加的运行循环源的模式

   );

   CFRelease(courceRef);

}

 

2. 设置回调函数

 

// socket回调函数的格式:

static void TCPServerConnectCallBack(CFSocketRefsocket, CFSocketCallBackType type, CFDataRef address, const void *data, void*info) {

    if (data != NULL) {

        // 当socket为kCFSocketConnectCallBack时,失败时回调失败会返回一个错误代码指针,其他情况返回NULL

        NSLog(@"连接失败");

        return;

    }

    TCPClient *client = (TCPClient *)info;

    // 读取接收的数据

    [info performSlectorInBackground:@selector(readStream) withObject:nil];

3. 接收发送数据

// 读取接收的数据

- (void)readStream {

    char buffer[1024];

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    while (recv(CFSocketGetNative(_socket), //与本机关联的Socket 如果已经失效返回-1:INVALID_SOCKET

           buffer, sizeof(buffer), 0)) {

        NSLog(@"%@", [NSString stringWithUTF8String:buffer]);

    }

}

// 发送数据

- (void)sendMessage {

     NSString*stringTosend = @"你好";

    char *data = [stringTosend UTF8String];

    send(SFSocketGetNative(_socket), data, strlen(data) + 1, 0);

}

服务器端:

CFSockteRef _socket;

CFWriteStreamRef outputStream = NULL;

int setupSocket() {

    _socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM,IPPROTO_TCP, kCFSocketAcceptCallBack, TCPServerAcceptCallBack, NULL);

    if (NULL == _socket) {

        NSLog(@"Cannot create socket!");

        return 0;

    }

   

    int optval = 1;

    setsockopt(CFSocketGetNative(_socket), SOL_SOCKET, SO_REUSEADDR, // 允许重用本地地址和端口

(void *)&optval, sizeof(optval));

   

    struct sockaddr_in addr4;

    memset(&addr4, 0, sizeof(addr4));

    addr4.sin_len = sizeof(addr4);

    addr4.sin_family = AF_INET;

    addr4.sin_port = htons(port);

    addr4.sin_addr.s_addr = htonl(INADDR_ANY);

    CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8*)&addr4, sizeof(addr4));

   

    if (kCFSocketSuccess != CFSocketSetAddress(_socket, address)) {

        NSLog(@"Bind to address failed!");

        if (_socket)

              CFRelease(_socket);

        _socket = NULL;

        return 0;

    }

       

    CFRunLoopRef cfRunLoop = CFRunLoopGetCurrent();

    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,_socket, 0);

    CFRunLoopAddSource(cfRunLoop, source, kCFRunLoopCommonModes);

    CFRelease(source);

   

    return 1;

}

// socket回调函数,同客户端

void TCPServerAcceptCallBack(CFSocketRefsocket, CFSocketCallBackType type, CFDataRef address, const void *data, void*info) {

    if (kCFSocketAcceptCallBack == type) {

        // 本地套接字句柄

        CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;

        uint8_t name[SOCK_MAXADDRLEN];     

        socklen_t nameLen = sizeof(name);

        if (0 != getpeername(nativeSocketHandle, (struct sockaddr *)name,&nameLen)) {

            NSLog(@"error");

            exit(1);

        }

        NSLog(@"%@ connected.", inet_ntoa( ((struct sockaddr_in*)name)->sin_addr )):

        CFReadStreamRef iStream;

        CFWriteStreamRef oStream;

        // 创建一个可读写的socket连接

         CFStreamCreatePairWithSocket(kCFAllocatorDefault,nativeSocketHandle, &iStream, &oStream);

        if (iStream && oStream) {

            CFStreamClientContext streamContext = {0, NULL, NULL, NULL};

            if (!CFReadStreamSetClient(iStream, kCFStreamEventHasBytesAvaiable,

                                       readStream, // 回调函数,当有可读的数据时调用

                                       &streamContext)){

                 exit(1);

            }

            if (!CFReadStreamSetClient(iStream, kCFStreamEventCanAcceptBytes,writeStream, &streamContext)){

                 exit(1);

            }

            CFReadStreamScheduleWithRunLoop(iStream, CFRunLoopGetCurrent(),kCFRunLoopCommomModes);

            CFWriteStreamScheduleWithRunLoop(wStream, CFRunLoopGetCurrent(),kCFRunLoopCommomModes);

            CFReadStreamOpen(iStream);

            CFWriteStreamOpen(wStream);

        } else {

              close(nativeSocketHandle);

        }

     }

}

// 读取数据

void readStream(CFReadStreamRef stream,CFStreamEventType eventType, void *clientCallBackInfo) {

    UInt8 buff[255];

    CFReadStreamRead(stream, buff, 255);

    printf("received: %s", buff);

}

void writeStream (CFWriteStreamRef stream, CFStreamEventTypeeventType, void *clientCallBackInfo) {

    outputStream = stream;

}

main {

    char *str = "nihao";

   

    if (outputStream != NULL) {

        CFWriteStreamWrite(outputStream, str, strlen(line) + 1);

    } else {

        NSLog(@"Cannot send data!");

    }

}

// 开辟一个线程线程函数中

void runLoopInThread() {

    int res = setupSocket();

    if (!res) {

        exit(1);

    }

    CFRunLoopRun();    // 运行当前线程的CFRunLoop对象

}

 
 

iOS socket,布布扣,bubuko.com

iOS socket

标签:des   style   blog   http   使用   os   io   文件   

原文地址:http://www.cnblogs.com/wudan7/p/3912250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!