2 // ITInetServerSocket.m
5 // Created by Alexander Strange on Thu Feb 13 2003.
6 // Copyright (c) 2003 __MyCompanyName__. All rights reserved.
9 #import "ITInetServerSocket.h"
10 #import "ITInetSocket.h"
13 #import <netinet/in.h>
14 #import <sys/socket.h>
18 @interface ITInetServerSocket(Private)
19 -(void)setupConnectionWithServiceName:(NSString*)name;
20 -(void)setupConnectionWithPortNumber:(NSNumber*)port;
21 -(void)setupRendezvousAdvertising:(NSString*)name;
23 -(void)timerFunc:(NSTimer*)timer;
26 @implementation ITInetServerSocket
29 if (self = [super init])
32 delegate = clients = nil;
37 - (id)initWithServiceName:(NSString*)name delegate:(id)d
39 if (self = [super init])
41 delegate = [d retain];
42 clients = [[NSMutableSet alloc] init];
43 [self setupConnectionWithServiceName:name];
48 - (id)initWithPort:(NSNumber*)port rendezvousName:(NSString*)name delegate:(id)d
50 if (self = [super init])
52 delegate = [d retain];
53 clients = [[NSMutableSet alloc] init];
54 [self setupConnectionWithPortNumber:port];
84 @implementation ITInetServerSocket(Private)
85 -(void)setupConnectionWithServiceName:(NSString*)name
87 const char *_name = [name cString];
88 struct addrinfo hints,*res;
90 hints.ai_flags = AI_PASSIVE;
91 hints.ai_family = PF_INET;
92 hints.ai_socktype = SOCK_STREAM;
93 hints.ai_protocol = IPPROTO_TCP;
95 hints.ai_canonname = NULL;
99 getaddrinfo(NULL,_name,&hints,&res);
100 sockfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol);
101 bind(sockfd, res->ai_addr, res->ai_addrlen);
102 listen(sockfd, SOMAXCONN);
103 fcntl(sockfd,F_SETFL,O_NONBLOCK);
107 -(void)setupConnectionWithPortNumber:(NSNumber*)port
109 short _port = [port shortValue];
110 struct sockaddr_in sa;
112 sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
113 sa.sin_addr.s_addr = INADDR_ANY;
114 sa.sin_family = AF_INET;
115 sa.sin_port = htons(_port);
116 bind(sockfd,(struct sockaddr *)&sa,sizeof(sa));
117 listen(sockfd, SOMAXCONN);
118 fcntl(sockfd,F_SETFL,O_NONBLOCK);
121 - (void)setupRendezvousAdvertising:(NSString*)name port:(NSNumber*)port
123 service = [[NSNetService alloc] initWithDomain:@"" type:[NSString stringWithFormat:@"_%@._tcp.",name] port:htons([port shortValue])];
129 NSTimer *timer = [NSTimer timerWithTimeInterval:0 target:self selector:@selector(timerFunc:) userInfo:nil repeats:YES];
130 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
133 - (void)timerFunc:(NSTimer*)timer
135 struct sockaddr_in csa;
139 cfd = accept(sockfd,(struct sockaddr*)&csa,&csalen);
141 if (errno == EWOULDBLOCK) return;
142 else {perror("Too bad I haven't implemented error checking yet");}
145 ITInetSocket *csocket = [[[ITInetSocket alloc] initWithFD:cfd delegate:self] autorelease];
146 [clients addObject:csocket];
147 [delegate newClientJoined:csocket];