views:

43

answers:

0

Hi, I have a problem with my socket program. I create the client program (my code is below) I have a problem when i close the socket with the disconnect method. Can i help me? Thanks and sorry for my English XP

    CFSocketRef s;


        -(void)CreaConnessione
        {
            CFSocketError errore;

            struct sockaddr_in sin;

            CFDataRef address;
            CFRunLoopSourceRef source;

            CFSocketContext context = { 0, self, NULL, NULL, NULL };

            s = CFSocketCreate(
                               NULL, 
                               PF_INET,
                               SOCK_STREAM, 
                               IPPROTO_TCP, 
                               kCFSocketDataCallBack, 
                               AcceptDataCallback, 
                               &context);

            memset(&sin, 0, sizeof(sin));

            int port = [fieldPorta.text intValue];
            NSString *tempIp = fieldIndirizzo.text;
            const char *ip = [tempIp UTF8String];

            sin.sin_family = AF_INET;
            sin.sin_port = htons(port);
            sin.sin_addr.s_addr = (long)inet_addr(ip);

            address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin));
            errore = CFSocketConnectToAddress(s, address, 0);

            if(errore == 0){
                buttonInvioMess.enabled = TRUE;
                fieldMessaggioInvio.enabled = TRUE;

                labelTemp.text = [NSString stringWithFormat:@"Connesso al Server"];

                CFRelease(address);

                source = CFSocketCreateRunLoopSource(NULL, s, 0);
                CFRunLoopAddSource(CFRunLoopGetCurrent(), 
                                   source, 
                                   kCFRunLoopDefaultMode);

                CFRelease(source);
                CFRunLoopRun();
            }

            else{
                labelTemp.text = [NSString stringWithFormat:@"Errore di connessione. Verificare Ip e Porta"];
                switchConnection.on = FALSE; 
            }

        }



        //the socket doesn't disconnect
-(void)Disconnetti{

            CFSocketInvalidate(s);
            CFRelease(s);
        }


        -(IBAction)Connetti
        {
            if(switchConnection.on)
                [self   CreaConnessione];
            else
                [self   Disconnetti];

        }