IOS 局域网发送信息

基于ios 例子WiTap

1.创建本地的服务并设置监听时间检测是否有设备连接。

NSNetService  * server = [[NSNetService alloc] initWithDomain:@"local." type:kWiTapBonjourType name:@"Minwei" port:0];
//[UIDevice currentDevice].name
if(self.server != nil) {
  [self.server setDelegate:self];
   //self.server.includesPeerToPeer = YES;
   [self.server publishWithOptions:NSNetServiceListenForConnections];
   [self.server scheduleInRunLoop:[NSRunLoop currentRunLoop]forMode:NSRunLoopCommonModes];
   //[self.server publish];
}

2.创建本地的客户端搜索服务。

testServiceBrowser = [[NSNetServiceBrowser alloc] init];
[testServiceBrowser setDelegate:self];
//testServiceBrowser.includesPeerToPeer = YES;
[testServiceBrowser searchForServicesOfType:kWiTapBonjourType inDomain:@"local"];

3当查找到服务的时候会调用以下方法,寻找和移除来确定局域网里面有多少个IP连接上。

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveService:(NSNetService *)service moreComing:(BOOL)moreComing
{
    //[netService removeObject:service];
    if(!moreComing){
        NSLog(@"remove");
        [netServices removeObject:service];
    }
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing
{
    // Only update the UI once we get the no-more-coming indication.
    //[netService addObject:service];
    if(!moreComing){
        NSLog(@"find");
        [service setDelegate:self];
        [netServices addObject:service];
        //[service resolveWithTimeout:5.0];
    }
}

4.通过打开NSInputStream和NSOutputStream来进行对第一个配对上的用户进行连接

BOOL success;
NSInputStream *     inStream;
NSOutputStream *    outStream;
success = [service getInputStream:&inStream outputStream:&outStream];
if ( ! success ) {
  //进行重新连接
} else {
  self.inputStream  = inStream;
  self.outputStream = outStream;
            
  [self openStreams];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
#pragma unused(stream)
    
    switch(eventCode) {
            
        case NSStreamEventOpenCompleted: {
            self.streamOpenCount += 1;
            assert(self.streamOpenCount <= 2);
            // Once both streams are open we hide the picker and the game is on.
            if (self.streamOpenCount == 2) {
                //连接成功
            }
        } break;
            
        case NSStreamEventHasSpaceAvailable: {
            assert(stream == self.outputStream);
            // do nothing
        } break;
            
        case NSStreamEventHasBytesAvailable: {
       //回调信息成功 uint8_t b; NSInteger bytesRead; assert(stream
== self.inputStream); bytesRead = [self.inputStream read:&b maxLength:sizeof(uint8_t)]; if (bytesRead <= 0) { // Do nothing; we‘ll handle EOF and error in the // NSStreamEventEndEncountered and NSStreamEventErrorOccurred case, // respectively. } else { if(b!=#){ passMessage[inum] = b; inum++; } else{ printf("%s", (char *)passMessage); NSString *result = [NSString stringWithCString:(char *)passMessage encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); inum =0; } return; } } break; default: assert(NO); // fall through case NSStreamEventErrorOccurred: // fall through case NSStreamEventEndEncountered: {//重新查询链接 } break; } }

附 openStreams ,closeStreams和发送信息

- (void)openStreams
{
    assert(self.inputStream != nil);            // streams must exist but aren‘t open
    assert(self.outputStream != nil);
    assert(self.streamOpenCount == 0);
    
    [self.inputStream  setDelegate:self];
    [self.inputStream  scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream  open];
    
    [self.outputStream setDelegate:self];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream open];
}

- (void)closeStreams
{
    assert( (self.inputStream != nil) == (self.outputStream != nil) );      // should either have both or neither
    if (self.inputStream != nil) {
        [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.inputStream close];
        self.inputStream = nil;
        
        [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.outputStream close];
        self.outputStream = nil;
    }
    self.streamOpenCount = 0;
}

send 方法

- (void)send:(uint8_t)
{
    NSLog(@"send");
    assert(self.streamOpenCount == 2);
    // Only write to the stream if it has space available, otherwise we might block.
    // In a real app you have to handle this case properly but in this sample code it‘s
    // OK to ignore it; if the stream stops transferring data the user is going to have
    // to tap a lot before we fill up our stream buffer (-:
    
    if ( [self.outputStream hasSpaceAvailable] ) {
        
        NSInteger bytesWritten;
        NSUInteger dataLength;
        
        NSUInteger soFar = 0;
        NSInteger written = 0;
        
        
        NSData * data = [@"qwertitiww#" dataUsingEncoding:NSUTF8StringEncoding];
        const uint8_t * m = (Byte*)[data bytes];
        dataLength = [data length];
        
        do{
            
            bytesWritten = [self.outputStream write:&m[soFar] maxLength:dataLength - soFar];
            assert(bytesWritten!=0);
            if(written ==-1){
                break;
            }
            else{
                soFar += bytesWritten;
            }
            if (bytesWritten != dataLength) {
                [self setupForNewGame];
                break;
            }
            
        }while (soFar != dataLength);
    }
}

由于传输只能接受uint8_t所以需要传送一个bytes来传送字符串  在最后#号是结束符来区分时候传送完一个信息

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。