2
我用類似這樣的客戶端代碼:OS X/iOS&TCP:爲什麼CFSocketSendData在連接重置後調用時會崩潰應用程序?
#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>
void receiveData(CFSocketRef s,
CFSocketCallBackType type,
CFDataRef address,
const void *data,
void *info)
{
CFDataRef df = (CFDataRef) data;
int len = CFDataGetLength(df);
if(len <= 0) return;
CFRange range = CFRangeMake(0,len);
UInt8 buffer[len];
NSLog(@"Received %d bytes from socket %d\n",
len, CFSocketGetNative(s));
CFDataGetBytes(df, range, buffer);
NSLog(@"Client received: %s\n", buffer);
NSLog(@"As UInt8 coding: %@", df);
}
int main()
{
CFSocketRef s = CFSocketCreate(NULL, PF_INET,
SOCK_STREAM, IPPROTO_TCP,
kCFSocketDataCallBack,
receiveData,
NULL);
struct sockaddr_in sin;
struct hostent *host;
host = gethostbyname("********");
memset(&sin, 0, sizeof(sin));
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(888);
CFDataRef address, data;
UInt8 message[] = "Hello world";
CFRunLoopSourceRef source;
address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin));
data = CFDataCreate(NULL, message, sizeof(message));
CFSocketConnectToAddress(s, address, 0);
CFSocketSendData(s, NULL, data, 0);
CFRelease(address);
CFRelease(data);
source = CFSocketCreateRunLoopSource(NULL, s, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
source,
kCFRunLoopDefaultMode);
CFRelease(source);
CFRelease(s);
CFRunLoopRun();
}
它發送數據,並得到響應正常。但是TCP不應該只是發送數據,它應該發送數據RELIABLY。
我測試這樣的年表:
- 客戶端調用
CFSocketConnectToAddress
- 服務器授權客戶端
- 但是現在服務器應用程序崩潰,並且服務器 - >客戶端發送RST標誌。
- 之後,客戶撥打
CFSocketSendData
。
我預計CFSocketSendData
返回錯誤或至少拋出異常,但它會導致應用程序崩潰,並且@ try-catch不起作用。
什麼是崩潰? – Paulw11