La costruzione e l'invio di dati binari su rete
-
24-10-2019 - |
Domanda
Io sono la creazione di un client a riga di comando per Minecraft. C'è una specifica completa sul protocollo che può essere trovato qui: http://mc.kev009.com/Protocol. Per rispondere alla tua domanda in anticipo, sì, io sono un po 'di C ++ niubbo.
Ho diversi problemi in attuazione del presente protocollo, di cui ogni critica.
- Il protocollo dice che tutti i tipi sono big-endian. Non ho idea di come dovrei controllare se i miei dati sono little-endian e se sì come convertire in big-endian.
- Il tipo di dati stringa è uno strano un bit. È una stringa modificata UTF-8 che è preceduta da una breve contenente la lunghezza della stringa. Non ho idea di come dovrei confezionare questo in un semplice array char [] né come convertire i miei semplici stringhe in UTF-8 quelli modificati.
- Anche se sapessi come convertire i miei dati al big-endian e creare modificati stringhe UTF-8 io ancora non so come imballare questo in su in un array di caratteri [] e inviare questo come un pacchetto. Tutto quello che ho fatto prima è semplice rete HTTP che è ASCII.
Le spiegazioni, collegamenti, i nomi delle funzioni correlate e frammenti corti molto apprezzati!
Modifica
1 e 3 si risponde ora. 1 sia risolta seguito da user470379. 3 è risposta da questa discussione impressionante che spiega quello che voglio fare molto bene: http://cboard.cprogramming.com/networking-device-communication/68196-sending-non-char*-data.html non sono sicuro circa l'UTF modificato 8 ancora però.
Soluzione
Un approccio tradizionale è quello di definire un C ++ struttura del messaggio per ciascun messaggio di protocollo e implementare funzioni di serializzazione e deserializzazione per esso. Per esempio Accesso Richiesta può essere rappresentato in questo modo:
#include <string>
#include <stdint.h>
struct LoginRequest
{
int32_t protocol_version;
std::string username;
std::string password;
int64_t map_seed;
int8_t dimension;
};
sono necessarie funzioni di serializzazione Now. In primo luogo ha bisogno di funzioni di serializzazione per gli interi e stringhe, dal momento che questi sono i tipi di membri in LoginRequest
.
funzioni di serializzazione Integer bisogno di fare conversioni da e per big-endian rappresentazione. Dal momento che i membri del messaggio vengono copiati e dal buffer, l'inversione dell'ordine di byte può essere fatto durante la copia:
#include <boost/detail/endian.hpp>
#include <algorithm>
#ifdef BOOST_LITTLE_ENDIAN
inline void xcopy(void* dst, void const* src, size_t n)
{
char const* csrc = static_cast<char const*>(src);
std::reverse_copy(csrc, csrc + n, static_cast<char*>(dst));
}
#elif defined(BOOST_BIG_ENDIAN)
inline void xcopy(void* dst, void const* src, size_t n)
{
char const* csrc = static_cast<char const*>(src);
std::copy(csrc, csrc + n, static_cast<char*>(dst));
}
#endif
// serialize an integer in big-endian format
// returns one past the last written byte, or >buf_end if would overflow
template<class T>
typename boost::enable_if<boost::is_integral<T>, char*>::type serialize(T val, char* buf_beg, char* buf_end)
{
char* p = buf_beg + sizeof(T);
if(p <= buf_end)
xcopy(buf_beg, &val, sizeof(T));
return p;
}
// deserialize an integer from big-endian format
// returns one past the last written byte, or >buf_end if would underflow (incomplete message)
template<class T>
typename boost::enable_if<boost::is_integral<T>, char const*>::type deserialize(T& val, char const* buf_beg, char const* buf_end)
{
char const* p = buf_beg + sizeof(T);
if(p <= buf_end)
xcopy(&val, buf_beg, sizeof(T));
return p;
}
E per archi (movimentazione modificato UTF-8 allo stesso modo come stringhe ASCIIZ ):
// serialize a UTF-8 string
// returns one past the last written byte, or >buf_end if would overflow
char* serialize(std::string const& val, char* buf_beg, char* buf_end)
{
int16_t len = val.size();
buf_beg = serialize(len, buf_beg, buf_end);
char* p = buf_beg + len;
if(p <= buf_end)
memcpy(buf_beg, val.data(), len);
return p;
}
// deserialize a UTF-8 string
// returns one past the last written byte, or >buf_end if would underflow (incomplete message)
char const* deserialize(std::string& val, char const* buf_beg, char const* buf_end)
{
int16_t len;
buf_beg = deserialize(len, buf_beg, buf_end);
if(buf_beg > buf_end)
return buf_beg; // incomplete message
char const* p = buf_beg + len;
if(p <= buf_end)
val.assign(buf_beg, p);
return p;
}
E un paio di funtori helper:
struct Serializer
{
template<class T>
char* operator()(T const& val, char* buf_beg, char* buf_end)
{
return serialize(val, buf_beg, buf_end);
}
};
struct Deserializer
{
template<class T>
char const* operator()(T& val, char const* buf_beg, char const* buf_end)
{
return deserialize(val, buf_beg, buf_end);
}
};
Ora, usando queste funzioni primitive che possiamo facilmente serializzare e deserializzare messaggio LoginRequest
:
template<class Iterator, class Functor>
Iterator do_io(LoginRequest& msg, Iterator buf_beg, Iterator buf_end, Functor f)
{
buf_beg = f(msg.protocol_version, buf_beg, buf_end);
buf_beg = f(msg.username, buf_beg, buf_end);
buf_beg = f(msg.password, buf_beg, buf_end);
buf_beg = f(msg.map_seed, buf_beg, buf_end);
buf_beg = f(msg.dimension, buf_beg, buf_end);
return buf_beg;
}
char* serialize(LoginRequest const& msg, char* buf_beg, char* buf_end)
{
return do_io(const_cast<LoginRequest&>(msg), buf_beg, buf_end, Serializer());
}
char const* deserialize(LoginRequest& msg, char const* buf_beg, char const* buf_end)
{
return do_io(msg, buf_beg, buf_end, Deserializer());
}
Usando i funtori helper sopra e rappresentano buffer di ingresso / uscita come char
iteratore varia solo modello funzione è necessaria per fare entrambe serializzazione e deserializzazione del messaggio.
E mettere tutto insieme, l'utilizzo:
int main()
{
char buf[0x100];
char* buf_beg = buf;
char* buf_end = buf + sizeof buf;
LoginRequest msg;
char* msg_end_1 = serialize(msg, buf, buf_end);
if(msg_end_1 > buf_end)
; // more buffer space required to serialize the message
char const* msg_end_2 = deserialize(msg, buf_beg, buf_end);
if(msg_end_2 > buf_end)
; // incomplete message, more data required
}
Altri suggerimenti
Per 1 #, avrete bisogno di utilizzare ntohs
e gli amici. Utilizzare le versioni (breve) *s
per interi a 16 bit, e la *l
(lunghe) versioni per interi a 32 bit. Il hton*
(host alla rete) ti permette di convertire i dati in uscita al big-endian indipendentemente dalla endianness della piattaforma si è in, e ntoh*
(rete per host) converte di nuovo i dati in ingresso (di nuovo, indipendentemente dalla piattaforma endianness)
fuori dalla parte superiore della mia testa ...
const char* s; // the string you want to send
short len = strlen(s);
// allocate a buffer with enough room for the length info and the string
char* xfer = new char[ len + sizeof(short) ];
// copy the length info into the start of the buffer
// note: you need to hanle endian-ness of the short here.
memcpy(xfer, &len, sizeof(short));
// copy the string into the buffer
strncpy(xfer + sizeof(short), s, len);
// now xfer is the string you want to send across the wire.
// it starts with a short to identify its length.
// it is NOT null-terminated.