2010-06-17 91 views
2

我正在爲iPad項目工作,它是一個小程序,我需要它與另一個在Windows上運行並且像服務器一樣運行的軟件進行通信;所以我爲iPad創建的應用程序將是客戶端。如何使用CFNetwork從套接字獲取字節數組?

我使用CFNetwork的做插座的溝通,這是我建立連接方式:

char ip[] = "192.168.0.244"; 
NSString *ipAddress = [[NSString alloc] initWithCString:ip]; 

/* Build our socket context; this ties an instance of self to the socket */ 
CFSocketContext CTX = { 0, self, NULL, NULL, NULL }; 

/* Create the server socket as a TCP IPv4 socket and set a callback */ 
/* for calls to the socket's lower-level connect() function */ 
TCPClient = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, (CFSocketCallBack)ConnectCallBack, &CTX); 

if (TCPClient == NULL) 
    return; 

/* Set the port and address we want to listen on */ 
struct sockaddr_in addr; 
memset(&addr, 0, sizeof(addr)); 
addr.sin_len = sizeof(addr); 
addr.sin_family = AF_INET; 
addr.sin_port = htons(PORT); 
addr.sin_addr.s_addr = inet_addr([ipAddress UTF8String]); 

CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr)); 
CFSocketConnectToAddress(TCPClient, connectAddr, -1); 
CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, TCPClient, 0); 
CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes); 
CFRelease(sourceRef); 
CFRunLoopRun(); 

這是我發送的數據,這基本上是一個字節數組

方式
/* The native socket, used for various operations */ 
// TCPClient is a CFSocketRef member variable 
CFSocketNativeHandle sock = CFSocketGetNative(TCPClient); 

Byte byteData[3]; 
byteData[0] = 0; 
byteData[1] = 4; 
byteData[2] = 0; 

send(sock, byteData, strlen(byteData)+1, 0); 

最後,你可能已經注意到,當我創建服務器套接字時,我註冊了一個kCFSocketDataCallBack類型的回調函數,這是代碼。

void ConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) 
{ 
    // SocketsViewController is the class that contains all the methods 
    SocketsViewController *obj = (SocketsViewController*)info; 

    UInt8 *unsignedData = (UInt8 *) CFDataGetBytePtr(data); 

    char *value = (char*)unsignedData; 
    NSString *text = [[NSString alloc]initWithCString:value length:strlen(value)]; 
    [obj writeToTextView:text]; 
    [text release]; 
} 

其實,這個回調被在我的代碼調用,問題是,我不知道我怎樣才能使Windows客戶端發過來的數據,我希望接收的字節數組,但我不知道如何從數據參數中獲取這些字節。

如果有人可以幫助我找到一個方法來做到這一點,也許我點我另一種方式來從服務器獲取數據在我的客戶端應用程序,我真的很感激。

謝謝。

回答

1

在您的回調中,data參數確實爲kCFSocketDataCallBack回調類型的CFDataRef值。

CFDataRef dataRef = (CFDataRef) data; 
Byte *array = new Byte[CFDataGetLength(dataRef)]; // Or use a fixed length 
CFDataGetBytes(dataRef, CFRangeMake(0, CFDataGetLength(theData)), array); 

array將包含字節數組。

相關問題