socket (tcp 局域网内)简单示例

这里使用的是第三方库 AsyncSocket。故使用时,

需要先添加第三方库,并添加静态库 CFNetWork.framework;并在实现类时,导入头文件  AsyncSocket.h

服务器端:

//1.初始化服务端socket

   AsyncSocket *serverSocket = [[AsyncSocket alloc]initWithDelegate:self];

//2.开启端口

   [serverSocket acceptOnPort:0x1234 error:nil];

//3.建立连接 ---实现代理方法     

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{

    NSLog(@"服务端--新的连接");

    if (socketArray==NULL) {

        socketArray=[NSMutableArray array];

    }

    [socketArray addObject:newSocket];

    [sock readDataWithTimeout:-1 tag:0];

    [newSocket readDataWithTimeout:-1 tag:0];

}

//4.读写数据 ---实现代理方法

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{

    NSLog(@"服务端--接收到数据");

    NSString *msgString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"msgString is %@",msgString);

    NSString *serverString=@"服务器返回的消息";

    [sock writeData:[serverString dataUsingEncoding:NSUTF8StringEncoding] withTimeout:5 tag:0];//发送数据

    [sock readDataWithTimeout:-1 tag:0];//读取数据

    

}

-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{

    NSLog(@"回复成功");

    [sock readDataWithTimeout:-1 tag:0];

}

//5.断开连接

[serverSocket disconnect];




客户端:

//1.初始化客户端socket

    AsyncSocket *clientSocket = [[AsyncSocket alloc]initWithDelegate:self];

//2.建立一个管道

    [clientSocket connectToHost:@"192.168.101.182" onPort:0x1234 withTimeout:-1 error:nil];

//3.实现代理方法

    

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{

    NSLog(@"客户端--已经连接到%@%d",host,port);

}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{

    NSLog(@"客户端--写入数据完成");

    [sock readDataWithTimeout:-1 tag:1];

}


- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{

    NSLog(@"客户端--收到数据");

    [sock readDataWithTimeout:-1 tag:1];

}

//4.发送数据

    NSString *msgString=@"发送的消息,哈哈哈";

    NSData *msgData=[msgString dataUsingEncoding:NSUTF8StringEncoding];

    [clientSocket writeData:msgData withTimeout:5 tag:1];

//5.断开连接

[clientSocket disconnect];


附:获取socket相关信息

- (NSString *)connectedHost;

- (UInt16)connectedPort;


- (NSString *)localHost;

- (UInt16)localPort;






你可能感兴趣的:(ios,tcp,socket)