我正在使用iPhone套接字进行一些测试。这是代码(它可以工作):
struct sockaddr_in destinationAddress;
socklen_t sockaddr_destaddr_len = sizeof(destinationAddress);
CFSocketError socket_error = 0;
CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault,
AF_INET,
SOCK_STREAM,
IPPROTO_TCP,
kCFSocketNoCallBack,
NULL,
NULL);
if (!socket) {
NSLog(@"CfSocketCreate Failed");
}
memset(&destinationAddress, 0, sockaddr_destaddr_len);
destinationAddress.sin_len = sockaddr_destaddr_len;
destinationAddress.sin_family = AF_INET;
destinationAddress.sin_port = htons(23678);
destinationAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
NSData *destinationAddressData = [NSData dataWithBytes:&destinationAddress length:sizeof(destinationAddress)];
NSString *message = @"data to send, new line\n";
NSData *message_data = [message dataUsingEncoding:NSUTF8StringEncoding];
CFSocketConnectToAddress(socket, (CFDataRef) destinationAddressData, 10);
socket_error = CFSocketSendData (socket, NULL, (CFDataRef) message_data, 10);
// show the status
if(socket_error < 0){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Socket situation"
message:@"Socket error"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
所以,首先我打开与另一个套接字(我的日志服务器)的连接。其次,我通过带有2nd NULL参数的CFSockectSendData发送数据,以便使用之前打开的连接。问题是当我尝试使用CFSocketSendData函数直接发送数据时,之前没有使用CFSocket CFSocketConnectToAddress函数。代码变为:
struct sockaddr_in destinationAddress;
socklen_t sockaddr_destaddr_len = sizeof(destinationAddress);
CFSocketError socket_error = 0;
CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault,
AF_INET,
SOCK_STREAM,
IPPROTO_TCP,
kCFSocketNoCallBack,
NULL,
NULL);
if (!socket) {
NSLog(@"CfSocketCreate Failed");
}
memset(&destinationAddress, 0, sockaddr_destaddr_len);
destinationAddress.sin_len = sockaddr_destaddr_len;
destinationAddress.sin_family = AF_INET;
destinationAddress.sin_port = htons(23678);
destinationAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
NSData *destinationAddressData = [NSData dataWithBytes:&destinationAddress length:sizeof(destinationAddress)];
NSString *message = @"data to send, new line\n";
NSData *message_data = [message dataUsingEncoding:NSUTF8StringEncoding];
socket_error = CFSocketSendData (socket, (CFDataRef) destinationAddressData, (CFDataRef) message_data, 10);
// show the status
if(socket_error < 0){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Socket situation"
message:@"Socket error"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
在这种情况下,我使用CFSocketSendData收集错误,并显示警报视图。错误是什么? 我只是删除了CFSocketConnectToAddress函数,因为第二个参数非NULL的CFSocketSendData应该能够连接到特定的地址。
答案 0 :(得分:0)
没有。 TCP是面向连接的协议。您必须先建立连接,然后才能发送任何数据。它不会为您“连接到特定地址”,因为能够指定目标地址的重点是能够为多个目标重用相同的套接字。如果用不同的地址调用CFSocketSendData()会发生什么?旧连接会关闭吗?如果没有,你如何在不关闭另一个连接的情况下关闭其中一个连接?
如果使用UDP(指定SOCK_DGRAM而不是SOCK_STREAM),则可以为每个数据包指定不同的地址。当然,请注意使用UDP的多个警告(无保证交付,无任何流量控制,您必须自己进行“连接管理”,因为没有UDP连接这样的事情。)
在这种情况下,我使用CFSocketSendData收集错误,并显示警报视图。错误是什么?
嗯,UIAlertView说了什么?