/*****
 NAME
 	cnetserver.m - source code for CNetServer
 VERSION
 	$Id$
 CHANGELOG
 	$Log$
 */

#include <coconut/gnet/cnetserver.h>
#include <coconut/cerror.h>

@implementation CNetServer

- init
{
	server_socket = NULL ;
	client_socket = NULL ;
	return [super init] ;
}

- (void) dealloc
{
	[self close] ;
	[super dealloc] ;
}

- (id <PError>) open: (int) portnum connect: (boolean) doconnect 
{
	server_socket = gnet_tcp_socket_server_new(portnum) ;
	if(server_socket == NULL)
		return [CError can_not_open] ;
	if(doconnect)
		return [self connect] ? nil : [CError can_not_open] ;
	else 
		return nil ;
}

- (id <PError>) close
{
	id <PError>	err ;
	err = [super closeChannel] ;
	if(err == nil){
		gnet_tcp_socket_delete(client_socket) ; client_socket = NULL ;
		gnet_tcp_socket_delete(server_socket) ; server_socket = NULL ;
	}
	return err ;
}

- (boolean) connect
{
	GIOChannel *	clientio ;

	client_socket = gnet_tcp_socket_server_accept(server_socket) ;
	if(client_socket == NULL)
		return FALSE ;
	clientio = gnet_tcp_socket_get_iochannel(client_socket) ;
	if(clientio){
		[self openChannel: clientio] ;
		return TRUE ;
	} else
		return FALSE ;
}

- (boolean) isServer
{
	return TRUE ;
}

@end

