我遇到与服务器连接的问题。我在下面给出了服务器代码。
- (void)startService
{
struct sockaddr_in addr;
int sockfd;
sockfd = socket( AF_INET, SOCK_STREAM, 0 );
bzero( &addr, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl( INADDR_ANY );
addr.sin_port = 0;
bind( sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
listen(sockfd, 5);
unsigned int namelen = sizeof(struct sockaddr_in);
getsockname( sockfd, (struct sockaddr *)&addr, &namelen );
listeningSocket = [[NSFileHandle alloc] initWithFileDescriptor:sockfd];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(openNewChatWindowAsMessageReceiver:)
name:NSFileHandleConnectionAcceptedNotification
object:listeningSocket];
[listeningSocket acceptConnectionInBackgroundAndNotify];
service = [[NSNetService alloc] initWithDomain:@"local."
type:@"_rce._tcp."
name:@""
port:addr.sin_port];
[service publish];
}
我正在尝试使用以下客户端应用代码连接服务器:
-(void)connectToServer{
NSNetService *remoteService = [discoveredServices objectAtIndex:[sender selectedRow]];
NSData *address = [[remoteService addresses] objectAtIndex:0];
// Create a socket that will be used to connect to the other chat client.
int s = socket(AF_INET, SOCK_STREAM, 0 );
if(connect( s, [address bytes], (int)[address length] )<0){
NSLog(@"connection Failed");
}else{
NSLog(@"connected");
}
}
这里的discoverservices是包含nsnetservicebrowser浏览的浏览服务列表的数组,如
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser
didFindService:(NSNetService *)aNetService
moreComing:(BOOL)moreComing
{
[discoveredServices addObject:aNetService];
}
在客户端应用程序我收到消息:连接失败.Plz给出建议。