我使用类似于此的客户端代码:
#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不应该只发送数据,它应该发送数据可靠。
我测试了这样的年表:
CFSocketConnectToAddress
CFSocketSendData
。我期望CFSocketSendData
返回错误或至少抛出异常,但它会导致应用程序崩溃,@ try-catch不起作用。
答案 0 :(得分:0)
你能尝试在第二个参数中使用显式地址吗?看看之后你是否收到错误。
CFSocketSendData(s ,, data,0);