socket在iOS上的应用

    xiaoxiao2025-06-09  22

    最近在做智能家居项目,需要用到socket的地方很多,TCP\UDP 

    其实在iOS端对于socket多半是作为客户端,然而其实客户端还是服务端 原理都是一样的

    iOS对socket需要了解相应概念,会运用(当然,深入理解概念更好)

    iOS本身有一套socket代码,不过在github上有一套大神封装好的socket可以直接使用

    这里主要介绍GCDAsyncSocket以及GCDAsyncUdpSocket

    TCP:

    1. 定义

    用一个队列去构建一个socket对象

     GCDAsyncSocket socketSend = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:delegateQueue socketQueue:socketQueue];

    2.连接

    用端口以及ip去连接服务端

    socketSend = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:delegateQueue socketQueue:soketQueue];

    3.方法

    1)发送数据

    socketSend writeData:<#(NSData *)#> withTimeout:<#(NSTimeInterval)#> tag:<#(long)#>

    2)连接成功后

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

    3)读取到数据后

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

    UDP

    udp我只用到了udp发送全局广播,主机收到消息后返回ip

    dispatch_async(dispatch_queue_create("myselfCommand", nil), ^{

            for (int i=0; i!=3; i++) {

                [socket sendData:data toHost:@"255.255.255.255" port:(u_int16_t)XIAOGUANJIATCPPORT withTimeout:-1 tag:0];

                sleep(3);

            }

        });

    收到消息后

    -(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{

    转载请注明原文地址: https://ju.6miu.com/read-1299775.html
    最新回复(0)