我一直在尝试在 iOS 上制作一个简单的应用程序,它将接收一条消息,然后根据该消息执行一个操作(目前我只想通过 显示它NSLog
)。我可以连接到服务,但服务似乎从来没有收到任何东西。这是我的 .h 文件:
#import <Foundation/Foundation.h>
#import <arpa/inet.h>
@interface PalServiceController : NSObject <NSNetServiceDelegate>
@property (nonatomic, strong) NSNetService *ns;
@property (nonatomic, strong) NSOutputStream *ostream;
- (void)start;
+ (int)getPort;
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode;
@end
和我的.m:
#import "PalServiceController.h"
@implementation PalServiceController
- (void)start
{
// Start a net service
int port = [PalServiceController getPort];
NSLog(@"Opening on port %i", port);
self.ns = [[NSNetService alloc] initWithDomain:@""
type:@"_TestingProtocol._tcp."
name:@"Test Name For iPhone"
port:port];
if (self.ns) {
[self.ns setDelegate:self];
[self.ns publish];
self.ns.delegate = self;
} else {
NSLog(@"Error starting service");
}
}
/*
* Code from: http://stackoverflow.com/a/11723158/657676
*/
+ (int) getPort
{
...
}
- (void)netServiceWillResolve:(NSNetService *)sender
{
NSLog(@"Resolving");
}
- (void)netServiceDidResolveAddress:(NSNetService *)sender
{
NSLog(@"Resolved Address");
}
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict
{
NSLog(@"Error publishing");
}
- (void)netService:(NSNetService *)sender didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream
{
NSLog(@"Got a connection! (server)");
// Close self down
[self.ns stopMonitoring];
[self.ns stop];
}
- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict
{
NSLog(@"Error resolving");
}
- (void)netServiceDidPublish:(NSNetService *)sender
{
NSLog(@"Published server");
}
- (void)netServiceDidStop:(NSNetService *)sender
{
NSLog(@"Server stopped");
}
- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data
{
NSLog(@"Updated TXT Record");
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
NSLog(@"Event on server");
switch(eventCode) {
...
}
}
@end
这通过以下方式调用:
self.controller = [[PalServiceController alloc] init];
[self.controller start];
当我使用Bonjour Browser时,我可以看到该服务,当我使用我自己的 an 实现NSNetServiceBrowser
或 Bill Dudney 的示例(博客文章,代码)时,它似乎已连接(即我自己的实现通过 接收NSStreamEventHasSpaceAvailable
和NSStreamEventOpenCompleted
事件stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
) . 但是,以上方法均未在服务器上调用。
我还是 iOS 新手,所以我希望这只是一些可以轻松修复的愚蠢错误。