我無法從正在開發的iphone應用程序在套接字上發送數據。 總之,我想連接到特定端口上的tcp服務器,發送數據有效負載,然後關閉套接字。打開套接字,發送數據,關閉套接字=截斷數據
看起來好像插座沒有在關閉之前刷新緩衝區中的數據。
這裏是我的代碼:
int port = 1234;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &readStream, &writeStream);
if (readStream && writeStream) {
//CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
inputStream = (NSInputStream *)readStream;
[inputStream retain];
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
outputStream = (NSOutputStream *)writeStream;
[outputStream retain];
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
}
[outputStream write:(void *)&len maxLength:4];
[outputStream write:[data bytes] maxLength:[data length]];
if (inputStream) {
CFReadStreamClose((CFReadStreamRef)inputStream);
CFRelease(inputStream);
}
if (outputStream) {
CFWriteStreamClose((CFWriteStreamRef)outputStream);
CFRelease(outputStream);
}
所有的想法都讚賞
延
你怎麼知道outputStream不發送任何東西?嘗試檢查'write:maxLength'的返回值。如果它是-1,則可以獲得調用'[outputStream streamError]''的更多細節。 – Saphrosit 2011-05-30 22:52:13
@PavelChuchuva它大部分時間都有效。我認爲,99%的發送通過我的服務器,但也許1%我連接到我的服務器,但沒有收到數據。 @ThomasMinor給了我下面的一些提示,這讓我最終在關閉套接字之前嘗試等待NSStreamEventHasSpaceAvailable事件,但是我不確定它是否有副作用。也許它會在發送大塊數據時關閉套接字?感謝您的幫助 – 2011-06-01 22:54:16