Objective c 使用SmallSockets从套接字读取数据会使我的应用程序崩溃

Objective c 使用SmallSockets从套接字读取数据会使我的应用程序崩溃,objective-c,cocoa,sockets,Objective C,Cocoa,Sockets,我正在使用SmallSockets库()创建一个应用程序 我有以下代码: #import "MAController.h" #import "Socket.h" @implementation MAController - (IBAction)doRequest:(id)sender { //Initialize NSURL *uUrl = [[NSURL alloc] initWithString:[tfHost stringValue]]; int

我正在使用SmallSockets库()创建一个应用程序

我有以下代码:

#import "MAController.h"
#import "Socket.h"


@implementation MAController

- (IBAction)doRequest:(id)sender
{
    //Initialize
    NSURL      *uUrl  = [[NSURL alloc] initWithString:[tfHost stringValue]];
    int         iPort = [[uUrl port] intValue];
    NSString   *sHost = [uUrl host];

    //Check
    if(sHost == NULL)
    {
        //Invalid Host name
        NSLog(@"Invalid Host name");
        NSAlert *aInvalidHost = [[[NSAlert alloc] init] autorelease];
        [aInvalidHost addButtonWithTitle:@"Ok"];
        [aInvalidHost setInformativeText:@"Invalid Host name"];
        [aInvalidHost setMessageText:@"You have entered an invalid host name. Please enter a valid host name."];
        [aInvalidHost setAlertStyle:NSInformationalAlertStyle];
        [aInvalidHost beginSheetModalForWindow:wMain modalDelegate:self didEndSelector:NULL contextInfo:nil];
        return;
    }
    if(iPort == 0)
    {
        iPort = 80;
    }

    //Create request
    NSString *sRequest = [[NSString alloc] initWithString:[tvRequest string]];

    //Create socket
    Socket *sSocket = [Socket socket];

    NSLog(@"Connecting...");
    [sSocket connectToHostName:sHost port:iPort];

    //Write request
    NSLog(@"Writing...");
    [sSocket writeString:sRequest];

    //Read response
    NSLog(@"Reading...");
    NSMutableData *mdResponse = [[[NSMutableData alloc] init] autorelease];

//IT CRASHES RIGHT HERE
    while([sSocket readData:mdResponse])
    {
        NSLog(@"Read.");
    }

    //Display response
    NSLog(@"Displaying...");
    NSString *sResponse = [[[NSString alloc] initWithData:mdResponse
                                             encoding:[NSString defaultCStringEncoding]]
                                             autorelease];
    [tvResponse setString:sResponse];

    [mdResponse release];
    [sSocket release];
}

@end
下面是我的调试器在单击触发doRequest操作的按钮后所说的话:

2009-10-24 18:22:19.197 iDebug HTTP[4836:a0f]正在连接…
2009-10-24 18:22:19.399 iDebug HTTP[4836:a0f]写作…
2009-10-24 18:22:19.400 iDebug HTTP[4836:a0f]正在阅读

主机名是
港口是80

谁能解释一下为什么我的应用程序在试图从套接字读取数据时挂起?提前谢谢


我没有安装防火墙。

因为您没有运行事件循环;你只是从插座上读。您没有显示
tvRequest
的文本是什么,但我猜服务器正在等待进一步的输入,而您正在等待它的输出

您可能会发现NSURLConnection更易于使用。它是异步的,这使得事件循环更容易处理,而请求和响应类是专门为简化HTTP而设计的