Sending packets to Minecraft server: Objective c

梦想的初衷 提交于 2020-01-04 06:38:10

问题


I've been trying to send packets to a minecraft server from my custom Cocoa application (written in objective-c of course). I am a little confused as how to do that though. I did it in Java. That was very easy. Doing this is objective-c though is proving to be a bit more challenging.

This is the code that I am using:

- (void)handshake
{
    PacketHandshake *packet = [PacketHandshake packetString:[NSString stringWithFormat:@"%@;%@:%i", username, IP, PORT]];
    [packet writeData:dataOut];
}

Which calls:

- (void)writeData:(NSOutputStream *)dataOut
{
    [super writeData:dataOut]; //Writes the "header" which is a char with the value of 0x02 (char packetID = 0x02)
    NSUInteger len = [string lengthOfBytesUsingEncoding:NSUTF16BigEndianStringEncoding]; //Getting the length of the string i guess?
    NSData *data = [string dataUsingEncoding:NSUTF16BigEndianStringEncoding]; //Getting string bytes?
    [dataOut write:(uint8_t*)len maxLength:2]; //Send the length?
    [dataOut write:[data bytes] maxLength:[data length]]; //Send the actual string?
}

I have established a successful connection to the server beforehand, but I don't really know whether or not I am sending the packets correctly. Could somebody please explain how I should send various data types and objects. (int, byte/char, short, double, NSString, BOOL/bool)

Also, is there any specific or universal way to send packets like the ones required by Minecraft?

Ok, I guess the question is now: how do data types, mainly strings, relate in Java and Objective-C?

Any help is appreciated, thank you!

Nobody knows?


回答1:


Maybe you're running into a network/host byte order problem? I know very little about Minecraft- but I note that it's mentioned here that shorts in the Minecraft protocol use network byte order, which is big-endian (all other data types are 1 byte long so endianness is not relevant). All x86 machines use little-endian.

I don't know whether your PacketHandshake class is converting the data before sending it- if not you could use the c library functions ntohs() and htons(), for which you'd need to include sys/types.h and netinet/in.h The link also mentions that strings are 64 byte array of standard ASCII chars, padded with 0x20s. You can get the ASCII value out of an NSString by doing [string UTF8String], which returns const char*- i.e. your standard C String ending with a 0x0, and then maybe pad it. But if it just works in Java, then maybe you don't need to.



来源:https://stackoverflow.com/questions/10859049/sending-packets-to-minecraft-server-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!