Documentação do Steamworks
steamnetworkingtypes.h
Tipos e funções diversos usados pelas APIs de rede.

Descrição de hosts de rede


Tipos necessários para descrever hosts de rede.

enum ESteamNetworkingIdentityType

Os diferentes tipos de identidades que um host remoto pode ter. No Steam, na maioria dos casos, será um CSteamID. Contudo, é possível desativar a autenticação; nesses casos, uma identidade mais genérica será usada.

enum ESteamNetworkingIdentityType //Comentarios traduzidos para melhor compreensao { // Simulado/desconhecido/invalido k_ESteamNetworkingIdentityType_Invalid = 0, // // Identificadores basicos especificos de plataforma. // k_ESteamNetworkingIdentityType_SteamID = 16, // CSteamID de 64 bits // // Identificadores especiais. // // Usa o endereco IP (e porta) como "identidade". // Esses tipos de identidade nunca são autenticadas. // Uteis ao migrar um codigo que faz uso de soquetes comuns, // e outras situacoes onde a autenticacao nao se faz necessaria. // Neste caso, a identidade local sera "localhost" // e o endereco remoto sera o endereco de rede. // // Usamos o mesmo tipo para IPv4 e IPv6, // armazenando o endereco no formato usado no IPv6. // Enderecos IPv4 sao mapeados de acordo. k_ESteamNetworkingIdentityType_IPAddress = 1, // Blobs de strings e binários genéricos. Cabe ao aplicativo interpreta-los. // A biblioteca pode indicar se o host remoto apresentou um certificado // assinado por alguem de sua confianca, com esta identidade. // Cabe a voce decidir o significado desta identidade. k_ESteamNetworkingIdentityType_GenericString = 2, k_ESteamNetworkingIdentityType_GenericBytes = 3, // Garanta que este enum sera armazenado em um int. k_ESteamNetworkingIdentityType__Force32bit = 0x7fffffff, }}

struct SteamNetworkingIdentity


Uma forma abstrata de representar a identidade de um host de rede.

struct SteamNetworkingIdentity // Comentarios traduzidos para melhor compreensao { /// Tipo da identidade. ESteamNetworkingIdentityType m_eType; // // Getters e setters em varios formatos. // void Clear(); bool IsInvalid() const; // Retorna true se formos do tipo invalido. Nao faz outras validacoes (ex.: se o ID Steam eh valido) void SetSteamID( CSteamID steamID ); CSteamID GetSteamID() const; // Retorna CSteamID preto (!IsValid()) se a identidade nao for um ID Steam void SetSteamID64( uint64 steamID ); // Aceita um ID Steam como um numero bruto de 64 bits uint64 GetSteamID64() const; // Retorna 0 se a identidade nao for um ID Steam void SetIPAddr( const SteamNetworkingIPAddr &addr ); // Define o endereco IP:porta especificado const SteamNetworkingIPAddr *GetIPAddr() const; // retorna null se nao formos um endereco IP. // "localhost" eh equivalente, em muitos propositos, a "anonymous". // O nosso par remoto nos identificara pelo endereco de rede que usarmos. void SetLocalHost(); // Define o endereco IP como localhost. (Sempre usamos o endereco IPv6 ::1 para este caso, e nao o endereco IPv4 127.0.0.1) bool IsLocalHost() const; // Retorna true se esta identidade for localhost. bool SetGenericString( const char *pszString ); // Retorna false se o tamanho for invalido const char *GetGenericString() const; // Retorna nullptr se nao for um tipo de string generico bool SetGenericBytes( const void *data, size_t cbLen ); // Retorna false se for de tamanho invalido. const uint8 *GetGenericBytes( int &cbLen ) const; // Retorna null se nao for de tipo de bytes invalido /// Verifica se duas identidades sao identicas bool operator==(const SteamNetworkingIdentity &x ) const; /// Gera uma string legivel por humanos. Util para mensagens de depuracao /// ou para quando precisar codificar a identidade como uma string. O formato eh similar /// a de um URL (type:<dados-do-tipo>). O buffer precisa ter, pelo menos, /// k_cchMaxString bytes de tamanho para evitar truncamento. void ToString( char *buf, size_t cbBuf ) const; /// Processa uma string gerada pela funcao ToString bool ParseString( const char *pszStr ); // Tamanhos maximos enum { k_cchMaxString = 128, // Tamanho maximo do buffer necessario para armazenar qualquer identidade formatada como string pela funcao ToString k_cchMaxGenericString = 32, // Tamanho maximo da string para identidades em formato de string generica, incluindo o '\0' terminador k_cbMaxGenericBytes = 32, }; // [] };

struct SteamNetworkingIPAddr


Armazena um endereço IP e uma porta.

Endereços IPv6 são sempre usados; endereços IPv4 são representados usando o "mapeamento para IPv4": IPv4 aa.bb.cc.dd => IPv6 ::ffff:aabb:ccdd. (Consulte o RFC 4291, seção 2.5.5.2.)
struct SteamNetworkingIPAddr // Comentarios traduzidos para melhor compreensao { void Clear(); // Define todos os valores como zero. Ex.: [::]:0 bool IsIPv6AllZeros() const; // Retorna true se o endereco IP for igual a ::0. (Nao verifica a porta.) void SetIPv6( const uint8 *ipv6, uint16 nPort ); // Define o endereco IPv6. O endereco IP eh interpretado como bytes, entao nao ha problemas de ordenacao. (Igual a inaddr_in6.) O endereco IP pode ser um endereco IPv4 mapeado void SetIPv4( uint32 nIP, uint16 nPort ); // Define o endereco IPv4 (que sera mapeado para IPv6 internamente). O endereco IP e porta usarao a ordem de bytes do host. bool IsIPv4() const; // Retorna true se o IP for um endereco IPv4 mapeado uint32 GetIPv4() const; // Retorna o endereco IP na ordem de bytes do host (ex.: aa.bb.cc.dd como 0xaabbccdd). Retorna 0 se o endereco IP nao for um endereco IPv4 mapeado. void SetIPv6LocalHost( uint16 nPort = 0); // Define o endereco IPv6 de localhost (::1) com a porta especificada. bool IsLocalHost() const; // Retorna true se esta identidade for localhost. (Seja ::1 do IPv6 ou 127.0.0.1 do IPv4) // Tamanho maximo do buffer necessario para armazenar o endereco IP e porta formatados como string pela funcao ToString, incluindo o '\0' terminador // ([0123:4567:89ab:cdef:0123:4567:89ab:cdef]:12345) enum { k_cchMaxString = 48 }; /// Gera uma string, com ou sem a porta. Enderecos IPv4 mapeados usam a representacao /// decimal separada por pontos (12.34.56.78). Outros enderecos usarao /// a representacao canonica, segundo o RFC5952. Caso inclua a porta, o endereco IPv6 estara envolvido /// por colchetes, ex.: [::1:2]:80. O buffer precisa ter, pelo menos, k_cchMaxString bytes /// de tamanho para evitar truncamento. inline void ToString( char *buf, size_t cbBuf, bool bWithPort ) const; /// Processa um endereco IP e, opcionalmente, uma porta. Se nao houver uma porta presente, o valor 0 sera usado. /// (Isso significa que nao da para verificar se uma porta zero foi especificada explicitamente.) inline bool ParseString( const char *pszStr ); union { uint8 m_ipv6[]; struct // Endereco IPv4 mapeado (rfc4038 secao 4.2) { uint64 m_8zeros; uint16 m_0000; uint16 m_ffff; uint8 m_ip[]; // OBS: Como bytes, ou seja, a ordem de bytes da rede } m_ipv4; }; uint16 m_port; // Ordem de bytes do host /// Verifica se dois enderecos sao identicos bool operator==(const SteamNetworkingIPAddr &x ) const; };

Estado da conexão

Os tipos a seguir são usados para descrever o estado de uma conexão. Consulte ISteamnetworkingSockets::GetConnectionInfo e SteamNetConnectionStatusChangedCallback_t.

enum ESteamNetworkingState

Enumera estados de conexão de alto nível.

enum ESteamNetworkingConnectionState // Comentarios traduzidos para melhor compreensao { /// Valor usado para indicar uma condicao de erro na API. /// A conexao especificada nao existe ou ja foi fechada. k_ESteamNetworkingConnectionState_None = 0, /// Estamos tentando estabelecer se os pares podem se comunicar, /// se QUEREM se comunicar, realizando autenticacao basica /// e trocando chaves criptograficas. /// /// - Para conexoes do lado do "cliente" (iniciadas localmente): /// Estamos no processo de tentativa de estabelecimento de conexao. /// Dependendo do tipo da conexao, podemos nao saber quem sao. /// Esteja ciente de que nao eh possivel saber se estamos aguardando /// a rede completar os pacotes de estabelecimento de conexao ou /// a camada de aplicacao aceitar a conexao. /// /// - Para conexoes do lado do "servidor" (aceitas por soquete de escuta): /// Completamos o estabelecimento basicoda conexao e o cliente apresentou /// alguma prova de identidade. A conexao esta pronta para ser aceita /// pela funcao AcceptConnection(). /// /// De qualquer forma, quaisquer pacotes nao confiaveis enviados agora /// quase certamente serao descartados. Tentativas de receber pacotes falharao. /// Voce pode enviar mensagens se o modo de envio permite enfileiramento, /// mas se fechar a conexao antes desta ser de fato estabelecida, /// todas as mensagens na fila serao descartadas imediatamente. /// (Nao tentaremos enviar tudo da fila e confirmar a entrega ao /// host remoto, o que normalmente acontece quando uma conexao eh fechada.) k_ESteamNetworkingConnectionState_Connecting = 1, /// Alguns tipos de conexao usam um canal secundario ou terceiro confiavel /// para as primeiras comunicacoes. Se o servidor aceitar a conexao, /// entao as conexoes entrarao em estado de encontro (rendezvous). /// Nesse estado, nao estabelecemos uma rota ponta a ponta (pela /// rede de retransmissores, logo mensagens nao confiaveis enviadas /// serao descartadas. k_ESteamNetworkingConnectionState_FindingRoute = 2, /// Recebemos comunicacoes do nosso par (e sabemos quem ele eh) /// e esta tudo certo. Caso feche a conexao agora, /// faremos de tudo para enviar todos os dados confiaveis /// cujo recebimento nao foi confirmado pelo par. (Mas observe que isso /// ocorre a nivel da aplicacao, entao diferentemente de uma conexao TCP, /// voce nao esta deixando que o sistema operacional cuide de tudo.) k_ESteamNetworkingConnectionState_Connected = 3, /// A conexao foi fechada pelo nosso par, mas nao foi fechada localmente. /// A conexao ainda existe a nivel de API. Voce precisara fechar /// o handle para liberar os recursos. Se houver mensagens na fila de entrada, /// voce pode recupera-las. Caso contrario, nao ha nada a se fazer com /// a conexao exceto fecha-la. /// /// Este estado eh similar ao CLOSE_WAIT em uma maquina de estados TCP. k_ESteamNetworkingConnectionState_ClosedByPeer = 4, /// Uma perturbacao na conexao foi detectada localmente. (ex.: tempo esgotado, /// problema com conexao local a internet etc.) /// /// A conexao ainda existe a nivel de API. Voce precisara fechar /// o handle para liberar os recursos. /// /// Tentativas de enviar outras mensagens falharao. Mensagens recebidas /// que estejam na fila estao disponiveis. k_ESteamNetworkingConnectionState_ProblemDetectedLocally = 5, // // Os valores a seguir sao usados internamente e nao serao retornados por qualquer API. // Eles estao documentados para dar uma ideia da maquina de estados usada por baixo // dos panos. // /// O nosso lado se desconectou e, a nivel de API, a conexao esta fechada. /// Nenhum outro dado pode ser enviado ou recebido. Todos os dados confiaveis foram enviados /// ou desistimos de envia-los e os descartamos. Ainda nao sabemos se o par sabe /// do fechamento da conexao, entao estamos esperando para ver se, caso recebamos /// um pacote dele, enviamos os pacotes apropriados para que ele saiba /// por que a conexao foi fechada (e nao depender de esgotamento de tempo, /// que da a aparencia de que algo deu errado). k_ESteamNetworkingConnectionState_FinWait = -1, /// O nosso lado se desconectou e, a nivel de API, a conexao esta fechada. /// Nenhum outro dado pode ser enviado ou recebido. A nivel de rede, por outro lado, /// nao indicamos ao par de que a conexao foi fechada. /// Estamos no processo de enviar todos os dados confiaveis. Depois disso, /// informaremos ao par que a conexao foi fechada e trocaremos para o estado /// FinWait. /// /// Observe que o host remoto nao eh avisado de que fechamos a conexao ate que /// os dados sejam enviados. Se o host remoto tentar nos enviar dados, faremos /// o necessario para manter a conexao aberta ate que possa ser fechada corretamente. /// Mas esses dados serao descartados, ja que nao havera como o aplicativo os ler. /// Isso nao costuma ser um problema, ja que protocolos de aplicacao que usam /// o recurso de finalizacao sao projetados para que o host remoto aguarde a resposta /// antes de enviar mais dados. k_ESteamNetworkingConnectionState_Linger = -2, /// A conexao foi desativada por completo e esta pronta para ser destruida k_ESteamNetworkingConnectionState_Dead = -3, k_ESteamNetworkingConnectionState__Force32Bit = 0x7fffffff };

enum ESteamNetConnectionEnd


Enumera várias causas de término de conexão. Esses valores foram projetados para funcionarem de forma similar a códigos de erro HTTP; o intervalo numérico dá uma boa ideia da fonte do problema.
enum ESteamNetConnectionEnd // Comentarios traduzidos para melhor compreensao { // Valor invalido/base k_ESteamNetConnectionEnd_Invalid = 0, // // Codigos especificos do aplicativo. Estes sao os valores que serao passados para a funcao // ISteamNetworkingSockets::CloseConnection. Voce pode usa-los se // quiser usar codigos especificos do aplicativo. Se nao precisar // dessa facilidade, voce pode usar o valor // k_ESteamNetConnectionEnd_App_Generic. // // A distincao entre termino "normal" e "excepcional" pode // ser usada se achar util, mas voce nao eh obrigado a usa-la // O unico lugar em que diferenciamos o normal e // excepcional eh nos dados analiticos de conexao. Se uma boa parte // das conexoes termina de forma excepcional, // um alerta pode ser disparado. // // 1xxx: Aplicativo terminou a conexao de forma "esperada". // Ex.: usuário escolheu se desconectar do servidor, // partida acabou normalmente etc. k_ESteamNetConnectionEnd_App_Min = 1000, k_ESteamNetConnectionEnd_App_Generic = k_ESteamNetConnectionEnd_App_Min, // Use codigos neste intervalo para desconexoes "normais" k_ESteamNetConnectionEnd_App_Max = 1999, // 2xxx: Aplicativo terminou a conexao de uma forma excepcional // ou inesperada, o que pode indicar um bug ou problema // de configuracao. // k_ESteamNetConnectionEnd_AppException_Min = 2000, k_ESteamNetConnectionEnd_AppException_Generic = k_ESteamNetConnectionEnd_AppException_Min, // Use codigos neste intervalo para desconexoes "inesperadas" k_ESteamNetConnectionEnd_AppException_Max = 2999, // // Codigos do sistema. Serao retornados pelo sistema quando // o estado da conexao for igual a k_ESteamNetworkingConnectionState_ClosedByPeer // ou k_ESteamNetworkingConnectionState_ProblemDetectedLocally. É proibido // passar um codigo neste intervalo para a funcao ISteamNetworkingSockets::CloseConnection // // 3xxx: Conexao falhou ou foi terminada por um problema com o // host local ou com a sua conexao a internet. k_ESteamNetConnectionEnd_Local_Min = 3000, // Operacao nao permitida porque voce esta no modo off-line. k_ESteamNetConnectionEnd_Local_OfflineMode = 3001, // Estamos tendo problemas em se comunicar com muitos (talvez todos) os retransmissores. // Como eh improvavel que todos ficaram off-line de uma vez, a melhor explicacao // eh de que ha um problema no nosso lado. Observe que nao // diferenciamos "muitos" e "todos" porque, na pratica, // demora para se detectar um problema de conexao, e, quando o tempo // da conexao se esgotar, nao podemos ter conseguido // verificar todos os clusters de retransmissores, mesmo se conseguimos // se comunicar com eles no passado. Assim, este codigo significa que: // // * Nao obtivemos comunicacao bem-sucedida com qualquer retransmissor recentemente; // * Ha evidencia de falhas recentes de comunicacao com varios retransmissores. k_ESteamNetConnectionEnd_Local_ManyRelayConnectivity = 3002, // Um servidor hospedado nao esta conseguindo se comunicar com o retransmissor // que o cliente estava usando, entao eh provavel que o problema // eh conosco k_ESteamNetConnectionEnd_Local_HostedServerPrimaryRelay = 3003, // Nao conseguimos obter a configuracao da rede. // Isso *quase* sempre eh um problema local, ja que a configuracao da rede // vem da CDN, que eh bem confiavel. k_ESteamNetConnectionEnd_Local_NetworkConfig = 3004, // O Steam rejeitou a requisicao por nao termos permissao // para realizar a operacao. k_ESteamNetConnectionEnd_Local_Rights = 3005, k_ESteamNetConnectionEnd_Local_Max = 3999, // 4xxx: Conexao falhou ou foi terminada, e a causa // NAO parece ser do host local ou a sua // conexao a internet. A causa pode ser do // host remoto ou de algo no meio dos dois. k_ESteamNetConnectionEnd_Remote_Min = 4000, // A conexao foi perdida, mas a nossa conexao aos servicos relevantes // (retransmissores) nao parece ter sido interrompida. Isso nao // significa que o problema eh "culpa deles", apenas que nao // parece que ha problemas com a nossa rede. k_ESteamNetConnectionEnd_Remote_Timeout = 4001, // Havia algo de invalido com o certificado ou os dados // criptograficos que me passou, nao reconheco ou aceito os seus tipos de chave, // etc. k_ESteamNetConnectionEnd_Remote_BadCrypt = 4002, // Voce me apresentou um certificado que pude processar // e *tecnicamente* podemos usar comunicacao criptografada, // mas houve um problema que me impede de verificar a sua identidade // ou garantir que ninguem possa interceptar a nossa comunicacao. // Ex.: sem a chave da autoridade certificadora (e nao aceito certificados nao assinados); // - Nao confio na chave da AC informada; // - O certificado nao esta restrito corretamente ao aplicativo, usuario, hora, datacenter etc.; // - O certificado nao fo emitido no seu nome. // - etc k_ESteamNetConnectionEnd_Remote_BadCert = 4003, // Nao pudemos se comunicar com o host remoto porque // o host remoto nao esta autenticado no Steam k_ESteamNetConnectionEnd_Remote_NotLoggedIn = 4004, // Nao pudemos se comunicar com o host remoto porque // nao estao executando o aplicativo correto. k_ESteamNetConnectionEnd_Remote_NotRunningApp = 4005, // Ha algo de errado com a versao do protocolo usada. // (Provavelmente o codigo que esta usando eh antigo.) k_ESteamNetConnectionEnd_Remote_BadProtocolVersion = 4006, k_ESteamNetConnectionEnd_Remote_Max = 4999, // 5xxx: Conexao falhou por algum outro motivo. k_ESteamNetConnectionEnd_Misc_Min = 5000, // Uma falha que nao necessariamente eh resultado de um bug no programa, // mas que deve ocorrer com tamanha raridade que nao vale a pena // ter um alerta ou texto localizado especifico para ela. // A string de depuracao deve conter mais detalhes. k_ESteamNetConnectionEnd_Misc_Generic = 5001, // Falha generica que eh provavel ser resultado de um bug no programa. k_ESteamNetConnectionEnd_Misc_InternalError = 5002, // O tempo de conexao ao host remoto se esgotou, // mas nao sabemos se o problema eh aqui, // do outro lado ou no meio. k_ESteamNetConnectionEnd_Misc_Timeout = 5003, // Nao estamos conseguindo nos comunicar com o retransmissor relevante. // Nao temos dados suficientes para dizer se o problema eh aqui // ou nao. k_ESteamNetConnectionEnd_Misc_RelayConnectivity = 5004, // Nao estamos conseguindo nos comunicar com o Steam. k_ESteamNetConnectionEnd_Misc_SteamConnectivity = 5005, // Um servidor de hospedagem dedicada nao possui sessoes de retransmissao // ativas com as quais pode se comunicar com um cliente. (O cliente eh // responsavel por abrir e manter essas sessoes.) k_ESteamNetConnectionEnd_Misc_NoRelaySessionsToClient = 5006, k_ESteamNetConnectionEnd_Misc_Max = 5999, };

SteamNetConnectionInfo_t


Describe the state of a connection.
struct SteamNetConnectionInfo_t // Comentarios traduzidos para melhor compreensao { /// Quem esta do outro lado? Dependendo do tipo de conexao e da fase da mesma, podemos nao saber SteamNetworkingIdentity m_identityRemote; /// Dados arbitrarios do usuario definidos pelo codigo local do aplicativo int64 m_nUserData; /// Handle do soquete de escuta associado a esta conexao, ou k_HSteamListenSocket_Invalid se iniciamos a conexao HSteamListenSocket m_hListenSocket; /// Endereco remoto. Pode ser 0 se nao sabemos qual ou se nao se aplicar ao caso. /// (ex.: basicamente tudo que nao seja uma conexao UDP direta.) SteamNetworkingIPAddr m_addrRemote; uint16 m__pad1; /// Em qual datacenter o host remoto esta hospedado? (0 se nao se sabe.) SteamNetworkingPOPID m_idPOPRemote; /// Qual retransmissor estamos usando para nos comunicar com o host remoto? /// (0 se nao se aplica ao caso.) SteamNetworkingPOPID m_idPOPRelay; /// Estado de alto nivel da conexao ESteamNetworkingConnectionState m_eState; /// Causa basica do termino ou problema com a conexao. /// Consulte ESteamNetConnectionEnd para saber os valores possiveis int m_eEndReason; /// Explicacao legivel para humanos, mas nao traduzida, do termino /// ou problema com a conexao. Util apenas para depuracao e /// diagnostico. Nao exiba este texto a usuarios. Pode /// conter alguns detalhes especificos do problema. char m_szEndDebug[]; /// Descricao para depuracao. Inclui o handle da conexao, /// tipo da conexao (e dados do par) e o nome do aplicativo. /// Esta string eh usada em varias mensagens de relatorio internas char m_szConnectionDescription[]; /// Dados internos, para facilitar alteracoes futuras na API uint32 reserved[64]; };

SteamNetworkingQuickConnectionStatus

Quick connection state, pared down to something you could call more frequently without it being too big of a perf hit.

struct SteamNetworkingQuickConnectionStatus //Comentarios traduzidos para melhor compreensao { /// Estado de alto nivel da conexao ESteamNetworkingConnectionState m_eState; /// Latencia atual (ms) int m_nPing; /// Qualidade da conexao, medida localmente. O valor estara no intervalo [0, 1], (representando a porcentagem /// de pacotes entregues na outra ponta em ordem). float m_flConnectionQualityLocal; /// Taxa de sucesso de entrega de pacotes segundo o host remoto float m_flConnectionQualityRemote; /// Taxas de dados atuais segundo o historico recente. float m_flOutPacketsPerSec; float m_flOutBytesPerSec; float m_flInPacketsPerSec; float m_flInBytesPerSec; /// Taxa de envio de bytes que acreditamos ser a maxima para o nosso par. /// Este valor pode ser bem maior que m_flOutBytesPerSec, /// ou seja, a capacidade do canal eh maior que a taxa sendo usada. /// (Mas nao ha problema!) int m_nSendRateBytesPerSecond; /// Quantidade de bytes na fila de envio. Estes sao dados cujo envio foi /// solicitado recentemente, mas ainda nao foram de fato enviados. /// A quantidade confiavel TAMBEM inclui dados enviados posteriormente, /// mas que foram preparados para retransmissao. Por isso, eh possivel que /// o valor de m_cbPendingReliable suba entre duas verificacoes, mesmo se /// nenhuma chamada foi feita para enviar dados confiaveis entre elas. Dados /// que estao esperando o atraso de Nagle entram na conta. int m_cbPendingUnreliable; int m_cbPendingReliable; /// Quantidade de bytes de dados confiaveis ja enviados, mas cuja /// confirmacao de recebimento nao chegou. Logo, eh possivel que /// precisem ser retransmitidos futuramente. int m_cbSentUnackedReliable; /// Caso peca que uma mensagem seja enviada agora, por quanto tempo ela /// ficaria na fila antes que os seus pacotes comecem a ser enviados? /// (E assumindo que Nagle nao cause o atraso de pacotes.) /// /// De forma geral, a taxa de envio de dados pela aplicacao eh limitada /// pela largura de banda do canal. Se enviar dados mais rapido que isso, /// eles entrarao na fila e serao enviados aos poucos. Even sending a small amount /// of data (e.g. a few MTU, say ~3k) will require some of the data to be delayed /// a bit. /// /// In general, the estimated delay will be approximately equal to /// /// ( m_cbPendingUnreliable+m_cbPendingReliable ) / m_nSendRateBytesPerSecond /// /// plus or minus one MTU. It depends on how much time has elapsed since the last /// packet was put on the wire. For example, the queue might have *just* been emptied, /// and the last packet placed on the wire, and we are exactly up against the send /// rate limit. In that case we might need to wait for one packet's worth of time to /// elapse before we can send again. On the other extreme, the queue might have data /// in it waiting for Nagle. (This will always be less than one packet, because as soon /// as we have a complete packet we would send it.) In that case, we might be ready /// to send data now, and this value will be 0. SteamNetworkingMicroseconds m_usecQueueTime; };

Network messages


const int k_cbMaxSteamNetworkingSocketsMessageSizeSend = 512 * 1024;
Max size of a single message that we can SEND.
Note: We might be wiling to receive larger messages, and our peer might, too.

SteamNetworkingMessage_t


A message that has been received
struct SteamNetworkingMessage_t { /// Message payload void *m_pData; /// Size of the payload. int m_cbSize; /// For messages received on connections: what connection did this come from? /// For outgoing messages: what connection to send it to? /// Not used when using the ISteamNetworkingMessages interface HSteamNetConnection m_conn; /// For inbound messages: Who sent this to us? /// For outbound messages on connections: not used. /// For outbound messages on the ad-hoc ISteamNetworkingMessages interface: who should we send this to? SteamNetworkingIdentity m_identityPeer; /// For messages received on connections, this is the user data /// associated with the connection. /// /// This is *usually* the same as calling GetConnection() and then /// fetching the user data associated with that connection, but for /// the following subtle differences: /// /// - This user data will match the connection's user data at the time /// is captured at the time the message is returned by the API. /// If you subsequently change the userdata on the connection, /// this won't be updated. /// - This is an inline call, so it's *much* faster. /// - You might have closed the connection, so fetching the user data /// would not be possible. /// /// Not used when sending messages, int64 m_nConnUserData; /// Local timestamp when the message was received /// Not used for outbound messages. SteamNetworkingMicroseconds m_usecTimeReceived; /// Message number assigned by the sender. /// This is not used for outbound messages int64 m_nMessageNumber; /// Function used to free up m_pData. This mechanism exists so that /// apps can create messages with buffers allocated from their own /// heap, and pass them into the library. This function will /// usually be something like: /// /// free( pMsg->m_pData ); void (*m_pfnFreeData)( SteamNetworkingMessage_t *pMsg ); /// Function to used to decrement the internal reference count and, if /// it's zero, release the message. You should not set this function pointer, /// or need to access this directly! Use the Release() function instead! void (*m_pfnRelease)( SteamNetworkingMessage_t *pMsg ); /// When using ISteamNetworkingMessages, the channel number the message was received on /// (Not used for messages sent or received on "connections") int m_nChannel; /// Bitmask of k_nSteamNetworkingSend_xxx flags. /// For received messages, only the k_nSteamNetworkingSend_Reliable bit is valid. /// For outbound messages, all bits are relevant int m_nFlags; /// Arbitrary user data that you can use when sending messages using /// ISteamNetworkingUtils::AllocateMessage and ISteamNetworkingSockets::SendMessage. /// (The callback you set in m_pfnFreeData might use this field.) /// /// Not used for received messages. int64 m_nUserData; /// You MUST call this when you're done with the object, /// to free up memory, etc. inline void Release(); };

Flags used for message sending

These values are used in bitmask parameters to functions such as ISteamNetworkingSockets::SendMessageToConnection

const int k_nSteamNetworkingSend_Unreliable = 0;
Send the message unreliably. Can be lost. Messages *can* be larger than a single MTU (UDP packet), but there is no retransmission, so if any piece of the message is lost, the entire message will be dropped.

The sending API does have some knowledge of the underlying connection, so if there is no NAT-traversal accomplished or there is a recognized adjustment happening on the connection, the packet will be batched until the connection is open again.

Migration note: This is not exactly the same as k_EP2PSendUnreliable! You probably want k_ESteamNetworkingSendType_UnreliableNoNagle

const int k_nSteamNetworkingSend_NoNagle = 1;
Disable Nagle's algorithm.

By default, Nagle's algorithm is applied to all outbound messages. This means that the message will NOT be sent immediately, in case further messages are sent soon after you send this, which can be grouped together. Any time there is enough buffered data to fill a packet, the packets will be pushed out immediately, but partially-full packets not be sent until the Nagle timer expires. See ISteamNetworkingSockets::FlushMessagesOnConnection, ISteamNetworkingMessages::FlushMessagesToUser

NOTE: Don't just send every message without Nagle because you want packets to "get there quicker". Make sure you understand the problem that Nagle is solving before disabling it. If you are sending small messages, often many at the same time, then it is very likely that it will be more efficient to leave Nagle enabled. A typical proper use of this flag is when you are sending what you know will be the last message sent for a while (e.g. the last in the server simulation tick to a particular client), and you use this flag to flush all messages.

const int k_nSteamNetworkingSend_UnreliableNoNagle = k_nSteamNetworkingSend_Unreliable|k_nSteamNetworkingSend_NoNagle;
Send a message unreliably, bypassing Nagle's algorithm for this message and any messages currently pending on the Nagle timer. This is equivalent to using steamnetworkingtypes::k_ESteamNetworkingSend_Unreliable and then immediately flushing the messages using ISteamNetworkingSockets::FlushMessagesOnConnection or ISteamNetworkingMessages::FlushMessagesToUser. (But using this flag is more efficient since you only make one API call.)

const int k_nSteamNetworkingSend_NoDelay = 4;
If the message cannot be sent very soon (because the connection is still doing some initial handshaking, route negotiations, etc), then just drop it. This is only applicable for unreliable messages. Using this flag on reliable messages is invalid.


const int k_nSteamNetworkingSend_UnreliableNoDelay = k_nSteamNetworkingSend_Unreliable|k_nSteamNetworkingSend_NoDelay|k_nSteamNetworkingSend_NoNagle;
Send an unreliable message, but if it cannot be sent relatively quickly, just drop it instead of queuing it. This is useful for messages that are not useful if they are excessively delayed, such as voice data.

A message will be dropped under the following circumstances:
  • the connection is not fully connected. (E.g. the "Connecting" or "FindingRoute" states)
  • there is a sufficiently large number of messages queued up already such that the current messagewill not be placed on the wire in the next ~200ms or so.

If a message is dropped for these reasons, k_EResultIgnored will be returned.

NOTE: The Nagle algorithm is not used, and if the message is not dropped, any messages waiting on the Nagle timer are immediately flushed.

const int k_nSteamNetworkingSend_Reliable = 8;
Reliable message send. Can send up to k_cbMaxSteamNetworkingSocketsMessageSizeSend bytes in a single message. Does fragmentation/re-assembly of messages under the hood, as well as a sliding window for efficient sends of large chunks of data.

The Nagle algorithm is used. See notes on k_ESteamNetworkingSendType_Unreliable for more details. See k_ESteamNetworkingSendType_ReliableNoNagle, ISteamNetworkingSockets::FlushMessagesOnConnection, ISteamNetworkingMessages::FlushMessagesToUser

Migration note: This is NOT the same as k_EP2PSendReliable, it's more like k_EP2PSendReliableWithBuffering

const int k_nSteamNetworkingSend_ReliableNoNagle = k_nSteamNetworkingSend_Reliable|k_nSteamNetworkingSend_NoNagle;
Send a message reliably, but bypass Nagle's algorithm.

Migration note: This is equivalent to k_EP2PSendReliable

Ping location / measurement

ISteamNetworkingutils has functions for estimating the ping time between two Internet hosts without sending any packets.

SteamNetworkingPingLocation_t


struct SteamNetworkPingLocation_t { uint8 m_data[]; }
Opaque object that describes a "location" on the Internet with sufficient detail that we can reasonably estimate an upper bound on the ping between the two hosts, even if a direct route between the hosts is not possible, and the connection must be routed through the Steam Datagram Relay network.

This does not contain any information that identifies the host. Indeed, if two hosts are in the same building or otherwise have nearly identical networking characteristics, then it's valid to use the same location object for both of them.

NOTE: This object should only be used in the same process! Do not serialize it, send it over the wire, or persist it in a file or database! If you need to do that, convert it to a string representation using the methods in ISteamNetworkingUtils

k_cchMaxSteamNetworkingPingLocationString


const int k_cchMaxSteamNetworkingPingLocationString = 1024;
Max possible length of a ping location, in string format. This is an extremely conservative worst case value which leaves room for future syntax enhancements. Most strings in practice are a lot shorter. If you are storing many of these, you will very likely benefit from using dynamic memory.

Configuration

You can control different operating parameters, on a global or connection-specific basis. The methdos to do this are in ISteamNetworkingUtils

ESteamNetworkingConfigScope


Configuration values can be applied to different types of objects.
enum ESteamNetworkingConfigScope { /// Get/set global option, or defaults. Even options that apply to more specific scopes /// have global scope, and you may be able to just change the global defaults. If you /// need different settings per connection (for example), then you will need to set those /// options at the more specific scope. k_ESteamNetworkingConfig_Global = 1, /// Some options are specific to a particular interface. Note that all connection /// and listen socket settings can also be set at the interface level, and they will /// apply to objects created through those interfaces. k_ESteamNetworkingConfig_SocketsInterface = 2, /// Options for a listen socket. Listen socket options can be set at the interface layer, /// if you have multiple listen sockets and they all use the same options. /// You can also set connection options on a listen socket, and they set the defaults /// for all connections accepted through this listen socket. (They will be used if you don't /// set a connection option.) k_ESteamNetworkingConfig_ListenSocket = 3, /// Options for a specific connection. k_ESteamNetworkingConfig_Connection = 4, };

ESteamNetworkingConfigDataType


Different configuration values have different data types
enum ESteamNetworkingConfigDataType { k_ESteamNetworkingConfig_Int32 = 1, k_ESteamNetworkingConfig_Int64 = 2, k_ESteamNetworkingConfig_Float = 3, k_ESteamNetworkingConfig_String = 4, k_ESteamNetworkingConfig_FunctionPtr = 5, // NOTE: When setting callbacks, you should put the pointer into a variable and pass a pointer to that variable. };

ESteamNetworkingConfigValue


Configuration options
enum ESteamNetworkingConfigValue { k_ESteamNetworkingConfig_Invalid = 0, /// [global float, 0--100] Randomly discard N pct of packets instead of sending/recv /// This is a global option only, since it is applied at a low level /// where we don't have much context k_ESteamNetworkingConfig_FakePacketLoss_Send = 2, k_ESteamNetworkingConfig_FakePacketLoss_Recv = 3, /// [global int32]. Delay all outbound/inbound packets by N ms k_ESteamNetworkingConfig_FakePacketLag_Send = 4, k_ESteamNetworkingConfig_FakePacketLag_Recv = 5, /// [global float] 0-100 Percentage of packets we will add additional delay /// to (causing them to be reordered) k_ESteamNetworkingConfig_FakePacketReorder_Send = 6, k_ESteamNetworkingConfig_FakePacketReorder_Recv = 7, /// [global int32] Extra delay, in ms, to apply to reordered packets. k_ESteamNetworkingConfig_FakePacketReorder_Time = 8, /// [global float 0--100] Globally duplicate some percentage of packets we send k_ESteamNetworkingConfig_FakePacketDup_Send = 26, k_ESteamNetworkingConfig_FakePacketDup_Recv = 27, /// [global int32] Amount of delay, in ms, to delay duplicated packets. /// (We chose a random delay between 0 and this value) k_ESteamNetworkingConfig_FakePacketDup_TimeMax = 28, /// [connection int32] Timeout value (in ms) to use when first connecting k_ESteamNetworkingConfig_TimeoutInitial = 24, /// [connection int32] Timeout value (in ms) to use after connection is established k_ESteamNetworkingConfig_TimeoutConnected = 25, /// [connection int32] Upper limit of buffered pending bytes to be sent, /// if this is reached SendMessage will return k_EResultLimitExceeded /// Default is 512k (524288 bytes) k_ESteamNetworkingConfig_SendBufferSize = 9, /// [connection int32] Minimum/maximum send rate clamp, 0 is no limit. /// This value will control the min/max allowed sending rate that /// bandwidth estimation is allowed to reach. Default is 0 (no-limit) k_ESteamNetworkingConfig_SendRateMin = 10, k_ESteamNetworkingConfig_SendRateMax = 11, /// [connection int32] Nagle time, in microseconds. When SendMessage is called, if /// the outgoing message is less than the size of the MTU, it will be /// queued for a delay equal to the Nagle timer value. This is to ensure /// that if the application sends several small messages rapidly, they are /// coalesced into a single packet. /// See historical RFC 896. Value is in microseconds. /// Default is 5000us (5ms). k_ESteamNetworkingConfig_NagleTime = 12, /// [connection int32] Don't automatically fail IP connections that don't have /// strong auth. On clients, this means we will attempt the connection even if /// we don't know our identity or can't get a cert. On the server, it means that /// we won't automatically reject a connection due to a failure to authenticate. /// (You can examine the incoming connection and decide whether to accept it.) k_ESteamNetworkingConfig_IP_AllowWithoutAuth = 23, // // Settings for SDR relayed connections // /// [int32 global] If the first N pings to a port all fail, mark that port as unavailable for /// a while, and try a different one. Some ISPs and routers may drop the first /// packet, so setting this to 1 may greatly disrupt communications. k_ESteamNetworkingConfig_SDRClient_ConsecutitivePingTimeoutsFailInitial = 19, /// [int32 global] If N consecutive pings to a port fail, after having received successful /// communication, mark that port as unavailable for a while, and try a /// different one. k_ESteamNetworkingConfig_SDRClient_ConsecutitivePingTimeoutsFail = 20, /// [int32 global] Minimum number of lifetime pings we need to send, before we think our estimate /// is solid. The first ping to each cluster is very often delayed because of NAT, /// routers not having the best route, etc. Until we've sent a sufficient number /// of pings, our estimate is often inaccurate. Keep pinging until we get this /// many pings. k_ESteamNetworkingConfig_SDRClient_MinPingsBeforePingAccurate = 21, /// [int32 global] Set all steam datagram traffic to originate from the same /// local port. By default, we open up a new UDP socket (on a different local /// port) for each relay. This is slightly less optimal, but it works around /// some routers that don't implement NAT properly. If you have intermittent /// problems talking to relays that might be NAT related, try toggling /// this flag k_ESteamNetworkingConfig_SDRClient_SingleSocket = 22, /// [global string] Code of relay cluster to force use. If not empty, we will /// only use relays in that cluster. E.g. 'iad' k_ESteamNetworkingConfig_SDRClient_ForceRelayCluster = 29, /// [connection string] For debugging, generate our own (unsigned) ticket, using /// the specified gameserver address. Router must be configured to accept unsigned /// tickets. k_ESteamNetworkingConfig_SDRClient_DebugTicketAddress = 30, /// [global string] For debugging. Override list of relays from the config with /// this set (maybe just one). Lista separada por virgula. k_ESteamNetworkingConfig_SDRClient_ForceProxyAddr = 31, // // Niveis de registro de dados de depuracao. A higher priority // (lower numeric value) will cause more stuff to be printed. // k_ESteamNetworkingConfig_LogLevel_AckRTT = 13, // [connection int32] RTT calculations for inline pings and replies k_ESteamNetworkingConfig_LogLevel_PacketDecode = 14, // [connection int32] log SNP packets send k_ESteamNetworkingConfig_LogLevel_Message = 15, // [connection int32] log each message send/recv k_ESteamNetworkingConfig_LogLevel_PacketGaps = 16, // [connection int32] dropped packets k_ESteamNetworkingConfig_LogLevel_P2PRendezvous = 17, // [connection int32] P2P rendezvous messages k_ESteamNetworkingConfig_LogLevel_SDRRelayPings = 18, // [global int32] Ping relays };

ESteamNetworkingGetConfigValueResult


Return value of ISteamNetworkintgUtils::GetConfigValue
enum ESteamNetworkingGetConfigValueResult { k_ESteamNetworkingGetConfigValue_BadValue = -1, // No such configuration value k_ESteamNetworkingGetConfigValue_BadScopeObj = -2, // Bad connection handle, etc k_ESteamNetworkingGetConfigValue_BufferTooSmall = -3, // Couldn't fit the result in your buffer k_ESteamNetworkingGetConfigValue_OK = 1, k_ESteamNetworkingGetConfigValue_OKInherited = 2, // A value was not set at this level, but the effective (inherited) value was returned. k_ESteamNetworkingGetConfigValueResult__Force32Bit = 0x7fffffff };

SteamNetworkingConfigValue_t


In a few places we need to set configuration options on listen sockets and connections, and have them take effect before the listen socket or connection really starts doing anything. Creating the object and then setting the options "immediately" after creation doesn't work completely, because network packets could be received between the time the object is created and when the options are applied. To set options at creation time in a reliable way, they must be passed to the creation function. This structure is used to pass those options.

For the meaning of these fields, see ISteamNetworkingUtils::SetConfigValue. Basically when the object is created, we just iterate over the list of options and call ISteamNetworkingUtils::SetConfigValueStruct, where the scope arguments are supplied by the object being created.
struct SteamNetworkingConfigValue_t { /// Which option is being set ESteamNetworkingConfigValue m_eValue; /// Which field below did you fill in? ESteamNetworkingConfigDataType m_eDataType; /// Option value union { int32_t m_int32; int64_t m_int64; float m_float; const char *m_string; // Points to your '\0'-terminated buffer void *m_functionPtr; } m_val; };

Valve data centers

Used to describe the topology of the Valve network, identify data centers, etc.

typedef uint32 SteamNetworkingPOPID;
Identifier used for a network location point of presence. (E.g. a Valve data center.)
Typically you won't need to directly manipulate these.

SteamNetworkingPOPID CalculateSteamNetworkingPOPIDFromString( const char *pszCode )
Converte um ID de 3 ou 4 caracteres em um inteiro de 32 bits.

template <int N> inline void GetSteamNetworkingLocationPOPStringFromID( SteamNetworkingPOPID id, char (&szCode)[N] )
Unpack integer to string representation, including terminating '\0'. Your string should be at least 5 bytes large. (It will fail to compile if this is not the case.)