此代码是有效的翻译。它当然可以改进,欢迎您提出意见,但它运行良好,并且完全符合 Python 代码的功能。
NSString * src = @"X.X.X.X";
NSString * mac = @"XX-XX-XX-XX-XX-XX";
const unsigned char byte64[] = {0x64};
const unsigned char byte00[] = {0x00};
NSString * srcString = [src base64EncodedString];
int srcDataLength = [srcString length];
char* srcDataLengthAsByte = (char*) &srcDataLength;
NSString * macString = [mac base64EncodedString];
int macDataLength = [macString length];
char* macDataLengthAsByte = (char*) &macDataLength;
NSString * remoteString = [remote base64EncodedString];
int remoteDataLength = [remoteString length];
char* remoteDataLengthAsByte = (char*) &remoteDataLength;
NSString * appString = [app base64EncodedString];
int appDataLength = [appString length];
char* appDataLengthAsByte = (char*) &appDataLength;
NSMutableData * msgData = [NSMutableData data];
[msgData appendBytes:byte64 length:1];
[msgData appendBytes:byte00 length:1];
[msgData appendBytes:srcDataLengthAsByte length:1];
[msgData appendBytes:byte00 length:1];
[msgData appendData:[srcString dataUsingEncoding:NSASCIIStringEncoding]];
[msgData appendBytes:macDataLengthAsByte length:1];
[msgData appendBytes:byte00 length:1];
[msgData appendData:[macString dataUsingEncoding:NSASCIIStringEncoding]];
[msgData appendBytes:remoteDataLengthAsByte length:1];
[msgData appendBytes:byte00 length:1];
[msgData appendData:[remoteString dataUsingEncoding:NSASCIIStringEncoding]];
int msgDataLength = [msgData length];
char* msgDataLengthAsByte = (char*) &msgDataLength;
NSMutableData * packet = [NSMutableData data];
[packet appendBytes:byte00 length:1];
[packet appendBytes:appDataLengthAsByte length:1];
[packet appendBytes:byte00 length:1];
[packet appendData:[appString dataUsingEncoding:NSASCIIStringEncoding]];
[packet appendBytes:msgDataLengthAsByte length:1];
[packet appendBytes:byte00 length:1];
[packet appendData:msgData];
[self send:packet];
和插座部分:
- (BOOL)connect
{
struct sockaddr_in addr;
sockfd = socket( AF_INET, SOCK_STREAM, 0 );
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr([TV_IP UTF8String]);
addr.sin_port = htons(TV_PORT);
return connect(sockfd, (struct sockaddr*)&addr, sizeof(addr))==0;
}
- (long)send:(NSData*)data
{
long sent = send(sockfd, [data bytes], [data length], 0);
VADebugLog(@"sent data:(%ld bytes) = [%@]",sent,[data description]);
return sent;
}
-(void)close
{
close(sockfd);
}
并包含来自: https://github.com/nicklockwood/Base64的 base64
#include <netinet/in.h>
#include <arpa/inet.h>
#import "Base64.h"