TCP/IP in Objective C?



我只是想在objective C或C中模仿下面的PHP,

<?php
$host="192.168.1.4";
$port = 1000;
$message="Hi";
// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp){
$result = "Error: could not open socket connection";
}
else{
fputs ($fp, $message);
fputs ($fp, "END");
fclose ($fp);
}
?>

我在Objective C中实现了以下内容,但这并不是那么可靠和快速,只有第一个消息得到传递,我需要重新连接第二个数据(我尝试过https://github.com/robbiehanson/CocoaAsyncSocket,但反映了与下面代码相同的结果)。我需要打开数据->发送数据->关闭连接(需要即时,没有任何延迟)

NSString *ipaddress =[NSString stringWithFormat:@"192.168.1.4"];
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)ipaddress, 1000, &readStream, &writeStream);
        inputStream = (NSInputStream *)readStream;
        outputStream = (NSOutputStream *)writeStream;
        [inputStream setDelegate:self];
        [outputStream setDelegate:self];
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
        [outputStream open];

我强烈建议使用更高级的框架进行网络通信。我一直在使用CocoaAsyncSocket在我的大多数项目中-比直接使用iOS的网络api少得多的脑损伤。

最新更新