[英]TCP/IP in Objective C?
我只是想在目標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更少的腦損傷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.