eval(art);

Cocoa TCPSockets

by Philippe Hausler on Dec.05, 2008, under MacOS X, Objective-C, iPhone/iPod Touch

Unfortunately Cocoa does not have native sockets that are universal enough to connect to other language built applications as a pre-built class. The server is intended to be a more thematic method for creating a server in Cocoa than the alternatives. The primary mechanic for connections being established, data incoming and connections closed are all based on delegate notifications by the TCPServerDelegate and TCPServerConnectionDelegate protocols. Data buffering, packet encapsulation and reachability are all upon the host application’s responsability to deal with. The server class set is intended to handle opening a TCP port for hosting, creating new connections to that TCP port, sending/receiving raw data, and Bonjour broadcasting. The TCPClient class also bends BSD sockets to preform similarly. The end result is a simple, easy to use socket server and client class which is portable from Mac OS X desktop to iPhone/iPod which can connect and transact with other applications such as software written for Windows.

Here is an example of a simple chat server.

@implementation TCPChatServer
- (id)init
{
	self = [super init];
	server = [[TCPServer alloc] init];
	server.delegate = self;
	[server listenOnPort:5543];
	[server broadcastOnDomain:@"" type:@"_tcpchat._tcp" name:@"My Chat Server"];
	[server publish];
	return self;
}
- (void)server:(TCPServer *)aServer didAcceptConnection:(TCPServerConnection *)aConnection
{
	aConnection.delegate = self;
}
- (void)connection:(TCPServerConnection *)aConnection didReceiveData:(NSData *)data
{
	[server write:data excluding:aConnection];
}
@end
 
@implementation TCPChatClient
- (id)init
{
	self = [super init];
	client = [[TCPClient alloc] init];
	client.delegate = self;
	return self;
}
- (void)connectToServer:(TCPHost *)host
{
	[client connectTo:host];
}
 
_ (void)send:(NSString *)msg
{
	[client write:[msg dataUsingEncoding:NSUTF8StringEncoding]];
}
 
- (void)client:(TCPClient *)aClient didReceiveData:(NSData *)data
{
	NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSLog(msg);
}
@end

TCPSockets.zip


Comments are closed.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...