unsigned char ngl_net_read_client(char num) { if (num==0) { if (SDLNet_TCP_Recv(csd0, buffer0, 512) > 0) { return 1; } return 0; } if (num==1) { if (SDLNet_TCP_Recv(csd1, buffer1, 512) > 0) { return 1; } return 0; } if (num==2) { if (SDLNet_TCP_Recv(csd2, buffer2, 512) > 0) { return 1; } return 0; } return 0; }
PMRECV PacketManager::Recv(TCPsocket socket, Uint16 *packetID, Uint16 *packetLength){ if(bufferSize<4)if(!Allocate(4))return PMRECV_ALLOCFAIL; Uint8 *buff = buffer; Uint16 len = 4; int ret = 0; while(len > 0){ ret = SDLNet_TCP_Recv(socket, buff, len); if((ret<=0)||(ret>len))return ((ret == 0)?PMRECV_DISCONNECT:PMRECV_ERROR); len -= ret; buff += ret; } lastPackID = SDLNet_Read16(buffer); lastPackLen = SDLNet_Read16(buffer + sizeof(Uint16)); Uint32 size = (Uint32)lastPackLen + 4; if((maxAllocSize != 0)&&(size > maxAllocSize))return PMRECV_OVERFLOW; if(size > bufferSize)if(!Allocate(size))return PMRECV_ALLOCFAIL; buff = buffer + 4; len = lastPackLen; ret = 0; while(len > 0){ ret = SDLNet_TCP_Recv(socket,buff,len); if((ret<=0)||(ret>len))return ((ret == 0)?PMRECV_DISCONNECT:PMRECV_ERROR); len -= ret; buff += ret; } dataLength = size; dataPos = 4; return PMRECV_SUCCESS; }
static int Treception(void *ptr) { Data data; /* buffer de réception */ DataList dataList; /* buffer de réception pour les listes de salles*/ DataGame dataGame; /* buffer de réception pour les données de jeu*/ int cnt; bool stopNetwork=false; while(!stopNetwork) { cnt = SDLNet_TCP_Recv(sd, &data, sizeof(Data)); if(cnt <= 0) return cnt; (*mCData)(&data); if(data.dataType == CONN) { if(data.car == SWITCH) // on nous prévient que une dataList va être transmise { do { cnt = SDLNet_TCP_Recv(sd, &dataList, sizeof(DataList)); (*mCList)(&dataList); } while(cnt>0 && !dataList.end); } else if(data.car == CONN_QUIT) stopNetwork = true; else if(data.car == CONN_ERROR) stopNetwork=true; else if(data.car == CONN_STOP) stopNetwork=true; } else if(data.dataType == GAME) { if(data.car == SWITCH) // on nous prévient que une dataGame va être transmise { if(waiting) { printf("reception thread is waiting main thread to switch to game\n"); while(waiting){} } cnt = SDLNet_TCP_Recv(sd, &dataGame, sizeof(DataGame)); (*mCGame)(&dataGame); } else if(data.car == GAME_ERROR) { stopNetwork=true; } } if(cnt <= 0) stopNetwork=true; } printf("Treception terminé\n"); return cnt; }
std::string TCPConnectionServer::ReadMessages( int connectionNr ) { if ( !CheckForActivity( connectionNr ) ) return ""; char buffer[1024]; memset( buffer, 0, bufferSize ); int byteCount = 0; std::string received(""); if ( isSocketConnected.size() < ( connectionNr + 1 ) ) return received; if ( isServer ) byteCount = SDLNet_TCP_Recv( serverSocket[connectionNr], buffer, bufferSize ); else byteCount = SDLNet_TCP_Recv( tcpSocket, buffer, bufferSize ); if ( byteCount > 0 ) { //memset( &buffer[byteCount], 0, static_cast< size_t > (512 - byteCount ) ); buffer[byteCount] = '\0'; received = buffer; if ( byteCount >= bufferSize ) { std::cout << "TCPConnection.cpp@" << __LINE__ << " Too much data received : " << byteCount << " / " << bufferSize << std::endl; } } // A bytecount of 0 means the connection has been terminated else if ( byteCount == 0 ) { std::cout << "TCPConnection.cpp@" << __LINE__ << " Connection terminated" << std::endl; isSocketConnected[ connectionNr ] = false; // A bytecount of < 0 means an error occured } else if ( byteCount < 0 ) { std::cout << "TCPConnection.cpp@" << __LINE__ << " Read failed!" << "\nSocket : " << ( isServer ? serverSocket[connectionNr] : tcpSocket ) << "\nByte count : " << byteCount << "\nError : " << SDLNet_GetError() << std::endl; } return received; }
char *network_read_string_1(TCPsocket sock) { uint8_t len; SDLNet_TCP_Recv(sock,&len,1); int read = 0; char *text = malloc(len+1); while (read != len) { int more = SDLNet_TCP_Recv(sock,text,len-read); if (more < 1) return 0; read += more; } text[len] = 0; return text; }
void NetworkManager::NetworkCommunicator() //make it receive paddlemanagers and ballmanagers to change positions into messages (break up server messages since it'll send ball and paddle to network... easy to write, not to read) { //call this from game loop int len; // commented out code should be correct (I can't check it yet though) once networking works right char buffer[512]; // char str[512]; if(!server) { //strcpy(buffer,NetworkManager::Vector3ToString(clientPaddle->getPosition())); len = strlen(buffer) + 1; if (SDLNet_TCP_Send(targetSocket, (void *)buffer, len) < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (SDLNet_TCP_Recv(targetSocket, buffer, 512) > 0) { std::string decode = std::string(buffer); unsigned found = decode.find_first_of("&"); Ogre::Vector3 v = NetworkManager::StringToVector3(buffer,0); //hostPaddle->setPosition(v); v = NetworkManager::StringToVector3(buffer,found+1); //ball->setPosition(v); printf("Host say: %s\n", buffer); } } else { if (SDLNet_TCP_Recv(targetSocket, buffer, 512) > 0) { Ogre::Vector3 v = NetworkManager::StringToVector3(buffer,0); //clientPaddle->setPosition(v); printf("Client say: %s\n", buffer); } //strcpy(str, NetworkManager::Vector3ToString(hostPaddle->getPosition())); strcat(str, " "); //strcat(str, NetworkManager::Vector3ToString(ball->getPosition())); strcpy(buffer,str); //strcpy(buffer,"test reply"); int len = strlen(buffer) + 1; if (SDLNet_TCP_Send(targetSocket, (void *)buffer, len) < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } } }
// receive a buffer from a TCP socket with error checking // this function handles the memory, so it can't use any [] arrays // returns 0 on any errors, or a valid char* on success char *getMsg(TCPsocket sock, char **buf) { Uint32 len,result; static char *_buf; // allow for a NULL buf, use a static internal one... if(!buf) buf=&_buf; // free the old buffer if(*buf) free(*buf); *buf=NULL; // receive the length of the string message result=SDLNet_TCP_Recv(sock,&len,sizeof(len)); if(result<sizeof(len)) { if(SDLNet_GetError() && strlen(SDLNet_GetError())) // sometimes blank! printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError()); return(NULL); } // swap byte order to our local order len=SDL_SwapBE32(len); // check if anything is strange, like a zero length buffer if(!len) return(NULL); // allocate the buffer memory *buf=(char*)malloc(len); if(!(*buf)){ return(NULL); } // get the string buffer over the socket result=SDLNet_TCP_Recv(sock,*buf,len); if(result<len) { if(SDLNet_GetError() && strlen(SDLNet_GetError())) // sometimes blank! printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError()); free(*buf); buf=NULL; } // return the new buffer return(*buf); }
int listenToCode(TCPsocket tcpclient, char *answer) { int brakets = 0; int i; char *data = MALLOCN(char, 4096); int size = 0; for (;;) { answer += size; size = SDLNet_TCP_Recv(tcpclient, data, 4095); data[size] = '\0'; memcpy(answer, data, size); for (i = 0; i < size; i++) { switch (answer[i]) { case '(': brakets++; break; case ')': brakets--; if (brakets == 0) { answer[i+1] = '\0'; return 0; } if (brakets < 0) return -1; break; } } } }
void NetClient::handleserver() { Uint8 data[512]; int pos, len; // int used; /* Has the connection been lost with the server? */ len = SDLNet_TCP_Recv(tcpsock, (char *)data, 512); if ( len <= 0 ) { SDLNet_TCP_DelSocket(socketset, tcpsock); SDLNet_TCP_Close(tcpsock); tcpsock = NULL; } else { pos = 0; while ( len > 0 ) { int used = handleserverdata(&data[pos]); pos += used; len -= used; if ( used == 0 ) { /* We might lose data here.. oh well, we got a corrupt packet from server */ len = 0; } } } }
int SDLNet_TCP_RecvLine(TCPsocket sock, char* data, int maxlen) { char c; int status = 0; int i = 0; while(1) { status = SDLNet_TCP_Recv(sock, &c, 1); if (status == -1) return -1; if (i == maxlen-1) return -1; if (status == 0) break; data[i] = c; i++; if (c == '\n') { data[i] = '\0'; return i; } } if(i > 0) { data[i] = '\0'; return i; } else { return 0; } }
/* Setup TCP Client, and attempt to connect * to the server */ int setup_client(unsigned port) { #if !defined(PSP) && !defined(EMSCRIPTEN) && !defined(DREAMCAST) && !defined(THREE_DS) is_client = 1; log_message(LOG_INFO, "Attempting to connect to server on port %u\n",port); //SDL_INIT(SDL_INIT_EVERYTHING); SDLNet_Init(); IPaddress ip; //TODO, for now always connect to localhost, fix for any specified ip in //the future SDLNet_ResolveHost(&ip, "localhost", port); client = SDLNet_TCP_Open(&ip); socketset = SDLNet_AllocSocketSet(1); char buf[100]; int i = SDLNet_TCP_Recv(client, buf, 100); for (int j = 0; j < i; j++) { printf("%c",buf[j]); } printf("\n"); SDLNet_TCP_AddSocket(socketset, client); connection_up = 1; return 1; #endif return 0; }
void mythVirtualServer::HandleClient(int which) { int closesocket; char data[4096] = {0}; //char tmpdata[512] = {0}; int datalength; int length; datalength = 0; for(;;){ length = SDLNet_TCP_Recv(people[which]->sock, data + datalength, 512); datalength += length; if(length < 512) break; } /* Has the connection been closed? */ if ( datalength <= 0 ) { #ifdef DEBUG fprintf(stderr, "Closing socket %d (was%s active)\n", which, people[which].active ? "" : " not"); #endif /* Notify all active clients */ closePeople(people[which]); } else { this->ServerDecodeCallBack(people[which],data,datalength); } }
/** read a packet from the given TCPsocket Returns -1 if some error occured, 0 if there was no data available and 1 if a packet was successfully read. Note: the socket has to be in the supplied socketset. TODO: this function will bomb if a packet arrives in pieces, there is no inherent guarantee that the next call will be made on the same socket. */ int grabPacket(TCPsocket s, SDLNet_SocketSet ss, struct NetPacket* pkt) { static char buf[NETPKTBUFSIZE]; static int buf_count = 0; int rc; if (SDLNet_CheckSockets(ss, 0) <= 0) return 0; if(!SDLNet_SocketReady(s)) return 0; rc = SDLNet_TCP_Recv(s, &buf[buf_count], NETPKTBUFSIZE - buf_count); if (rc <= 0) { /* closed connection? */ return -1; } else if (rc != NETPKTBUFSIZE) { /* we got a partial packet. Store what we got in the static buffer and return so that the next call can read the rest. Hopefully. */ buf_count = rc; return 0; } else { buf_count = 0; bufToPacket(buf, pkt); return 1; } }
int Server::script_client(void* data) throw(const char*){ Data_scriptClient* _data_cast=static_cast<Data_scriptClient*>(data); if(_data_cast==NULL){ throw "Impossibile eseguire il casting dei dati nello script client!"; } int bytes_rcv; char buffer[MAX_BYTES_BUFFER]; std::string data_store_rcv; std::string data_store_snd; int result; AppProtServer client_prot; while(_data_cast->exit==false){ bytes_rcv=SDLNet_TCP_Recv(_data_cast->connessione, buffer, MAX_BYTES_BUFFER); if(bytes_rcv<=0){ _data_cast->exit=true; }else{ data_store_rcv.append(buffer,bytes_rcv); result=client_prot.ElaboraRichiesta(data_store_rcv,data_store_snd); if(result){ int bytes_snd=SDLNet_TCP_Send(_data_cast->connessione, data_store_snd.data(), data_store_snd.size()); if(bytes_snd!=data_store_snd.size()){ _data_cast->exit=true; } } if(result==-1){ _data_cast->exit=true; } } } return 0; }
int network_tcp_recv(TCPsocket tcp, void* data, int maxlen) { int r = SDLNet_TCP_Recv(tcp, data, maxlen); if (r <= 0) { std::cerr << "Failed to recieve data over TCP: " << SDLNet_GetError() << "\n"; } return r; }
bool receiveTCP(TCPsocket socket, char *buffer, int size) { if (SDLNet_TCP_Recv(socket, buffer, size) > 0) return (true); return (false); }
/*一行読み込み*/ char* NetUtl_readLine(TCPsocket* sock){ //マルチスレッディングだとバグが出そうなんですが static char* buff = NULL; char ch; int buff_len = 0,length; //バッファクリア free(buff); buff = NULL; //ループ while((length = SDLNet_TCP_Recv(*sock, &ch, 1)) == 1){ if(ch == '\r')continue; buff = realloc(buff,buff_len+1); if(ch == '\n'){ buff[buff_len] = '\0'; break; } buff[buff_len] = ch; buff_len++; } //エラー if(length <= 0){ if(buff_len <= 0){ free(buff); buff = NULL; }else{ buff = realloc(buff,buff_len+1); buff[buff_len]='\0'; } } return buff; }
int clientConnection(TCPsocket *socketPekare) { client_send_information clientSendData; client_recieve_information clientRecieveData; int len1,len2; len1 = sizeof(clientSendData); len2 = sizeof(clientRecieveData); char serialiseradStruct1[len1]; char serialiseradStruct2[len2]; while(1) { SDL_Delay(10); convertSend(&clientSendData); memcpy(&serialiseradStruct1, &clientSendData, len1); SDLNet_TCP_Send(*socketPekare, &serialiseradStruct1, len1); SDL_Delay(10); SDLNet_TCP_Recv(*socketPekare,&serialiseradStruct2,len2); memcpy(&clientRecieveData,&serialiseradStruct2,len2); convertRecieve(&clientRecieveData); } return 0; }
int TCP_RECEIVEOBJ::read_tcp(char * readbuf, int size) { int len; bool reading=true; char tempbuf[readbuflength]; reading=true; readbuf[0]=0; while (reading) { if (SDLNet_CheckSockets(set, sockettimeout) == -1) return(TCP_BAD_REQUEST); if (SDLNet_SocketReady(sock)) { if ((len = SDLNet_TCP_Recv(sock, tempbuf, size)) <= 0) return(TCP_ERROR); tempbuf[len] = '\0'; if (strlen(readbuf) + strlen(tempbuf) <= (unsigned int)size) strcat (readbuf, tempbuf); if (strlen(readbuf)>=(unsigned int)size) reading=false; } else reading=false; } cout << readbuf; return (TCP_OK); }
//----------------------------------------------------------------------------- uint8_t* RecvData(int index, uint16_t* length, uint16_t* flag) { uint8_t temp_data[MAX_PACKET]; int num_recv = SDLNet_TCP_Recv(sockets[index], temp_data, MAX_PACKET); if(num_recv <= 0) { CloseSocket(index); const char* err = SDLNet_GetError(); if(strlen(err) == 0) { printf("DB: client disconnected\n"); } else { fprintf(stderr, "ER: SDLNet_TCP_Recv: %s\n", err); } return NULL; } else { int offset = 0; *flag = *(uint16_t*) &temp_data[offset]; offset += sizeof(uint16_t); *length = (num_recv-offset); uint8_t* data = (uint8_t*) malloc((num_recv-offset)*sizeof(uint8_t)); memcpy(data, &temp_data[offset], (num_recv-offset)); return data; } }
void NetServer::handleclient(int which) { char data[512]; int i; /* Has the connection been closed? */ if (SDLNet_TCP_Recv(clients[which].sock, data, 512) <= 0) { #ifdef _DEBUG printf("Closing socket %d (was%s active)\n", which, clients[which].active ? "" : " not"); #endif /* Notify all active clients */ if (clients[which].active) { clients[which].active = 0; data[0] = NET_MSG_DEL; data[NET_MSG_DEL_SLOT] = which; for (i = 0; i < MAXCLIENTS; ++i) { if (clients[i].active) { SDLNet_TCP_Send(clients[i].sock, data, 2); } } } SDLNet_TCP_DelSocket(socketset, clients[which].sock); SDLNet_TCP_Close(clients[which].sock); clients[which].sock = NULL; } else { switch (data[0]) { case NET_MSG_JOIN: { /* An active connection */ memcpy(clients[which].name, &data[NET_MSG_JOIN_NAME], 256); clients[which].name[256] = 0; #ifdef _DEBUG printf("Activating socket %d (%s)\n", which, clients[which].name); #endif /* Notify all active clients */ for (i = 0; i < MAXCLIENTS; ++i) { if (clients[i].active) { sendnewclientmessage(which, i); } } /* Notify about all active clients */ clients[which].active = 1; for (i = 0; i < MAXCLIENTS; ++i) { if (clients[i].active) { sendnewclientmessage(i, which); } } } break; default: { /* Unknown packet type?? */; } break; } } }
unsigned char MySocketConnection::read() { unsigned char c; int result = SDLNet_TCP_Recv(this->socket, &c, 1); if (result <= 0) { throw WAException(std::string(SDLNet_GetError()), WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); } return c; }
void Connection_recv_data(Connection* self, Uint8* buffer, int size) { if(SDLNet_TCP_Recv(self->socket, buffer, size) < size) { printf("Lost connection to server\n"); Connection_destroy(&self); } }
/** * Receive a Minecraft RCON packet through a connected TCP socket. * @param[in] rcon McRcon struct * @param[out] packetPtr Pointer to McRconPacket pointer. Will be set to a heap-allocated struct. * @return True if everything went ok, false if errors occured. */ static bool McRcon_ReceivePacket(McRcon* rcon, McRconPacket** packetPtr) { // Get packet size int32_t len; if (SDLNet_TCP_Recv(rcon->sock, &len, sizeof(int32_t)) <= 0) { McRcon_SetError(rcon, MC_RCON_ERR_NETWORK, SDLNet_GetError()); return false; } // Get packet data void* buffer = malloc(len); if (NULL == buffer) { McRcon_SetError(rcon, MC_RCON_ERR_MALLOC, NULL); return false; } if (SDLNet_TCP_Recv(rcon->sock, buffer, len) <= 0) { McRcon_SetError(rcon, MC_RCON_ERR_NETWORK, SDLNet_GetError()); return false; } // Cast received data to data struct McRconData* data = (McRconData*)buffer; // Pass the address of the payload field in McRconData as char pointer size_t payload_size = strlen((char*)(&(data->payload))); // Allocate sizeof(struct) + size of payload, which is terminated by two // null bytes McRconPacket* packet = malloc(sizeof(McRconPacket) + payload_size + 2); if (NULL == packet) { McRcon_SetError(rcon, MC_RCON_ERR_MALLOC, NULL); return false; } packet->len = len; packet->requestid = data->requestid; packet->type = data->type; strcpy(packet->payload, data->payload); free(data); *packetPtr = packet; return true; }
string game_host::recieveMessagep2() { char buff[512]; while(!SDLNet_TCP_Recv(this->player2sd, buff, 512)); //cout << buff << "\n"; string ret = buff; return ret; }
bool Client_recv_data(Client* self, Uint8* buffer, int size) { if(SDLNet_TCP_Recv(self->socket, buffer, size) < size) { return false; } return true; }
std::string TCPConnection::ReadMessages() { if ( !CheckForActivity() ) return ""; char buffer[bufferSize ]; memset( buffer, 0, bufferSize ); int byteCount = 0; std::string received(""); if ( !isConnected ) return received; if ( isServer ) byteCount = SDLNet_TCP_Recv( serverSocket, buffer, bufferSize ); else byteCount = SDLNet_TCP_Recv( tcpSocket, buffer, bufferSize ); if ( byteCount > 0 ) { //memset( &buffer[byteCount], 0, static_cast< size_t > (512 - byteCount ) ); buffer[byteCount] = '\0'; received = buffer; if ( byteCount >= bufferSize ) { logger->Log( __FILE__, __LINE__, " Too much data reciebed : ", byteCount ); logger->Log( __FILE__, __LINE__, " ...Buffer size is : ", bufferSize ); } } // A bytecount of 0 means the connection has been terminated else if ( byteCount == 0 ) { logger->Log( __FILE__, __LINE__, "Connection terminated : " ); Close(); // A bytecount of < 0 means an error occured } else if ( byteCount < 0 ) { logger->Log( __FILE__, __LINE__, "Read Failed : ", SDLNet_GetError() ); } return received; }
Uint8 Client_recv_flag(Client* self) { Uint8 flag; if(SDLNet_TCP_Recv(self->socket, &flag, 1) < 1) { return TCP_ERROR; } return flag; }
/* * network_tcp_recv() - Receive data via TCP from the given socket * @tcp: the socket to receive data from * @data: the pointer to store the data at * @maxlen: the maximum length of data to receive */ int network_tcp_recv(TCPsocket* tcp, void* data, int maxlen) { int r = SDLNet_TCP_Recv(*tcp, data, maxlen); // Attempt to receive the data if (r <= 0) { // If no data was received or another error occured std::cerr << "Failed to receive data over TCP: " << SDLNet_GetError() << "\n"; // Output the error message } return r; // Return the amount of data received on success, or the error code on failure }
static __inline__ int snTCPRead(TCPsocket s, Uint8 *buf, int max) { int val = -1; lockSDLNet(); val = SDLNet_TCP_Recv(s, buf, max); // read what we can unlockSDLNet(); return val; }