设置套接字流不起作用

时间:2016-01-03 16:03:32

标签: php ios objective-c sockets

是的,我想创建一个与我的服务器(TCP Open)的连接,我正在学习这个来自apple docs的tutorial(不,我不想使用其他项目)。以下是我的代码:

ViewController.h

@interface ViewController : UIViewController <NSStreamDelegate>{

}

@property (nonatomic, retain) NSInputStream *inputStream;

@property (nonatomic, retain) NSOutputStream *outputStream;

@end

ViewController.m

- (IBAction)searchForSite:(id)sender
{

    NSString *urlStr = @"http://mysitefake.com/host.php";
    if (![urlStr isEqualToString:@""]) {
        NSURL *website = [NSURL URLWithString:urlStr];
        if (!website) {
            NSLog(@"is not a valid URL");
            return;
        }

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[website host], 80, &readStream, &writeStream);

        inputStream = (__bridge_transfer NSInputStream *)readStream;
        outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [inputStream setDelegate:self];
        [outputStream setDelegate:self];
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
        [outputStream open];

        /* Store a reference to the input and output streams so that
         they don't go away.... */

    }
}

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {

    switch(eventCode) {
        case NSStreamEventHasSpaceAvailable:
        {
            NSLog(@"has space available");
            if (stream == outputStream) {
                NSLog(@"Equals");
                NSString * str = [NSString stringWithFormat:
                                  @"String to send to my server"];
                const uint8_t *rawstring = (const uint8_t *)[str UTF8String];
                [outputStream write:rawstring maxLength:10240];
                [outputStream close];
            }else{
                NSLog(@"Not equals");
            }
            break;
        }
           default:
           break;
    }
}

在我的服务器上有一个包含以下代码的PHP文件:

host.php

<?php
error_reporting(E_ALL);
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.mysitefake.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . 
         socket_strerror(socket_last_error()) . "\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . 
          socket_strerror(socket_last_error($socket)) . "\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.mysite.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

socket_close($socket);
?>

php文件的输出很好:

  

尝试在端口'80'上连接'Fake Ip'...发送HTTP   HEAD请求......好的。阅读回复:HTTP / 1.1 200 OK日期:太阳,3月3日   2016 15:53:10 GMT服务器:Apache Cache-Control:max-age = 31536000   到期日:2017年1月2日星期一15:53:10 GMT变化:   Accept-Encoding,User-Agent Connection:close Content-Type:text / html;   字符集= UTF-8

应用程序的输出是:

  

有空位吗?   等于

似乎发送了一些东西但是当我尝试在host.php中检查它时,我看不到发送的消息,在这种情况下是“发送到我的服务器的字符串”。

我的代码有问题吗?

1 个答案:

答案 0 :(得分:0)

我怀疑你有一个在端口80上运行的Apache Web服务器,可能托管你的PHP测试脚本。该应用程序正在打开与端口80的客户端连接,这意味着它将与Apache通信。您的PHP脚本也打开了与端口80的客户端连接,因此它也将连接到Apache(这将解释您在PHP日志中获得的Apache消息)。 你尝试建立连接的方式对我来说没有意义。通常,您将有一个应用程序作为服务器运行。这意味着它已在特定端口上打开侦听套接字。然后你有第二个应用程序打开到所述端口的客户端连接并发送一些初始数据。监听服务器将获取该数据并通过发回一些数据等作出反应。 您遵循的教程是设置与服务器的这种客户端连接。