Help Socket Programming

Discussion in 'Mac Programming' started by amit-battan, Nov 18, 2009.

  1. amit-battan macrumors newbie

    Joined:
    Sep 10, 2009
    #1
    Hi All

    I have to implement socket programming in our application...
    For this we have prepare a simple test application(server application)
    I used NSSocketPort and the following code...
    we followed this link http://macdevcenter.com/pub/a/mac/2006/11/14/how-to-write-a-cocoa-web-server.html


    SERVER CONTROLLER CLASS

    Code:
    #import "ServerController.h"
    @implementation ServerController
    -(IBAction)startStopConnectionAction:(id)sender{
    	if ([[sender title] isEqualToString:@"Start"]) {
    		[sender setTitle:@"Stop"];
    		NSLog(@"starting connection");
     
    		// allocating and initializing ServerModel class
    		if (serverModel) {
    			[serverModel release];
    		}
     
    		serverModel = [[ServerModel alloc] initWithPortNumber:25240 delegate:self];
    	}
       else{
    	    NSLog(@"stopping connection");
        }
    }
    @end
    

    SERVER MODEL CLASS

    Code:
    #import "ServerModel.h"
    @implementation ServerModel
    - (id)initWithPortNumber:(int)pn delegate:(id)delegatedObject{
    	NSLog(@"within initWithPortNumber: %d",pn);
    	if (self = [super init]) {
    		NSLog(@"within IF initWithPortNumber");
    		// initializing instance variables
    		portNumber = pn;
    		delegate = delegatedObject;
     
    		// establishing port to listen
    		serverSocketPort = [[NSSocketPort alloc] initWithTCPPort:portNumber];
    		int fd = [serverSocketPort socket];
    		NSLog(@"fd...%d",fd);
    		serverFileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd
    												   closeOnDealloc:YES];
     
    		NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    		[nc addObserver:self
    			   selector:@selector(newConnection:)
    				   name:NSFileHandleConnectionAcceptedNotification
    				 object:nil];
     
    		NSLog(@"nc...%@",nc);
    		[serverFileHandle acceptConnectionInBackgroundAndNotify];
    	}
     
    	return self;
    }
    - (void)dealloc{
    	NSLog(@"within dealloc");
        [[NSNotificationCenter defaultCenter] removeObserver:self];
     
        [serverFileHandle release];
        [serverSocketPort release];
        [delegate release];
        [super dealloc];
    }
     
    - (void)newConnection:(NSNotification *)notification{
    	NSLog(@"within newConnection:");
    	NSDictionary *userInfo = [notification userInfo];
    	NSLog(@"userInfo obtained- %@",userInfo);
    	NSFileHandle *remoteFileHandle = [userInfo objectForKey:
    									  NSFileHandleNotificationFileHandleItem];
     
    	NSNumber *errorNo = [userInfo objectForKey:@"NSFileHandleError"];
    	if( errorNo ) {
    		NSLog(@"NSFileHandle Error: %@", errorNo);
    		return;
    	}
     
    	NSLog(@"11111");
    	 [serverFileHandle acceptConnectionInBackgroundAndNotify];
     
    	if(remoteFileHandle){
    		NSData *dataReceieved = [remoteFileHandle availableData];
     
    		NSString *dataConvertedToString = [[NSString alloc] initWithData:dataReceieved encoding:NSASCIIStringEncoding];
     
    		NSLog(@"dataConvertedToString -%@",dataConvertedToString);
                    [remoteFileHandle writeData:dataReceieved];
    	}
     
    }
    @end
    

    to test this code I executed the telnet command on terminal...
    telnet 192.168.0.32 25240..
    192.168.0.32 is my machine IP, and 25240 port number defined in coding...

    Terminal Log
    Code:
    Amit:~ amitbattan$ telnet 192.168.0.32 25240
    Trying 192.168.0.32...
    Connected to 192.168.0.32.
    Escape character is '^]'.
    Testing Amit
    Testing Amit
    Connection closed by foreign host.
    
    I am sending a message 'Testing Amit' and get back it in terminal .. it is ok.. but after it connection gets closed ...
    as terminal give response 'Connection closed by foreign host.'

    Can anybody suggest me how we keep connected our connection as long as we required it..

    Thanks
    Amit Battan
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    Don't base it on such a simple example.

    First, HTTP is connectionless. There is no guarantee of a long-term connection. It is entirely possible that every request creates a new TCP/IP connection. It's unclear if you intend to implement an HTTP server or some other protocol. If it's HTTP, you must implement the protocol as it's specified, and that includes dealing with connection lifetime.

    Second, the notes and comments at the end of the article emphasize that the presented code is not a full-featured server. The author admits it's a simple server, and there are many things it just won't do. Some of the comments contain links to other example code:

    http://macdevcenter.com/pub/a/mac/2006/11/14/how-to-write-a-cocoa-web-server.html?page=4

    Third, Apple provides an example server that uses streams:

    http://developer.apple.com/samplecode/CocoaHTTPServer/

    Finally, if you want connections with a longer lifetime, you should look at AsyncSocket:

    http://code.google.com/p/cocoaasyncsocket/
     

Share This Page