void IRC::step(void) { if (!socket) return; while (1) { int check = SDLNet_CheckSockets(socketSet, 0); if (check == 0) { break; } else if (check == 1) { char data[IRC_MESSAGE_SIZE]; bool res=getString(data); if (res) { if (verbose) printf("YOG (IRC) has received [%s]\n", data); interpreteIRCMessage(data); } else { printf("YOG (IRC) has received an error\n"); break; } } else { printf("YOG (IRC) has a select error\n"); break; } } }
int Connection::recvWait(inp::INFPacket& dest, Uint32 ms){ SDL_LockMutex(pimpl_->dataAccess); if( (pimpl_->group == NULL) || (pimpl_->userSocket == NULL) ) { pimpl_->connectTime = 0; SDL_UnlockMutex(pimpl_->dataAccess); return -1; } Uint32 startTime = SDL_GetTicks(); int numReady; while( (SDL_GetTicks()-startTime) < ms ){ numReady = SDLNet_CheckSockets(pimpl_->group, 10); if( numReady == -1 ){ pimpl_->active = false; pimpl_->connectTime = 0; break; } if( SDLNet_SocketReady(pimpl_->userSocket) ){ pimpl_->active = true; SDL_UnlockMutex(pimpl_->dataAccess); return recv(dest); } } SDL_UnlockMutex(pimpl_->dataAccess); return -1; }
/* check if there's a message from the server */ void get_server_message () { int nr_active_sock, reclen, startptr = 0, msglen; try_again: nr_active_sock = SDLNet_CheckSockets (theset, 1); if (nr_active_sock == 0) return; if (!SDLNet_SocketReady (thesock)) return; reclen = get_packet (); if (reclen == -1) return; if (reclen <= 0) { log_error ("Disconnected by the server!\n"); exit_connection (EXIT_ALL); exit (1); } msglen = *((short *) (msgbuf + startptr + 1)); msglen += 2; if (process_message(msgbuf+startptr, msglen) == 0) { /* something went wrong when processing our message. Log out. */ exit_connection (EXIT_ALL); log_error ("Unable to process message"); exit (1); } goto try_again; }
void Users::process(){ int n = SDLNet_CheckSockets(set, 0); if (n < 1) return; if (SDLNet_SocketReady(sock)){ printf("new user...\n"); TCPsocket newuser = SDLNet_TCP_Accept(sock); printf("Accepted...\n"); User *u = new User(newuser); push_back(u); SDLNet_TCP_AddSocket(set,newuser); } User *u; for( iterator i = begin(); i != end(); i++ ){ u = *i; if (SDLNet_SocketReady(u->sock)){ int len; char buf[MAXLEN]; if ((len = readLine(u->sock,buf,sizeof(buf))) > 0){ fprintf(stderr,"got len=%d text from '%s': '%s'\n",len,u->name,buf); handle_command(buf,u); } else { printf("dead connection\n"); SDLNet_TCP_DelSocket(set, u->sock); SDLNet_TCP_Close(u->sock); i = erase(i); } } } }
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); }
static __inline__ int snCheckSockets(SDLNet_SocketSet ss, int wait) { int val = 0; val = SDLNet_CheckSockets(ss, wait); return val; }
int FCEUD_GetDataFromServer(uint8 *data) { uint8 buf[128]; NoWaiting&=~2; while(SDLNet_CheckSockets(set,1)==0) { // do something here. } if(SDLNet_SocketReady(Socket)) { if(de32(buf)==incounter) /* New packet, keep. */ { unsigned long beefie; memcpy(data,buf+TCPHEADSIZE,5); incounter++; if(!ioctl(Socket,FIONREAD,&beefie)) if(beefie) NoWaiting|=2; return(1); } } if(SDLNet_SocketReady(UDPSocket) { } }
bool ClientConnection::poll(packet_recv_callback message_handler, void* context, int timeout) { if (_client_socket == NULL) { fprintf(stderr, "ClientConnection::poll: Connection not initialized!\n"); return false; } while (true) { int nready = SDLNet_CheckSockets(_socket_set, timeout); timeout = 0; // Don't wait again on repeated checks if (nready < 0) { fprintf(stderr, "Error: SDLNet_CheckSockets reported %s\n", SDLNet_GetError()); return false; } else if (nready == 0) { break; } while (SDLNet_SocketReady(_client_socket)) { receiver_t receiver, sender; receive_packet(_client_socket, _packet_buffer, receiver, sender); if (message_handler && !_packet_buffer.empty()) { message_handler(sender, context, &_packet_buffer[HEADER_SIZE], _packet_buffer.size() - HEADER_SIZE); } } } return true; }
// ZZZ: the socket listening thread loops in this function. It calls the registered // packet handler when it gets something. static int receive_thread_function(void*) { while(true) { // We listen with a timeout so we can shut ourselves down when needed. int theResult = SDLNet_CheckSockets(sSocketSet, 1000); if(!sKeepListening) break; if(theResult > 0) { theResult = SDLNet_UDP_Recv(sSocket, sUDPPacketBuffer); if(theResult > 0) { if(take_mytm_mutex()) { ddpPacketBuffer.protocolType = kPROTOCOL_TYPE; ddpPacketBuffer.sourceAddress = sUDPPacketBuffer->address; ddpPacketBuffer.datagramSize = sUDPPacketBuffer->len; // Hope the other guy is done using whatever's in there! // (As I recall, all uses happen in sPacketHandler and its progeny, so we should be fine.) memcpy(ddpPacketBuffer.datagramData, sUDPPacketBuffer->data, sUDPPacketBuffer->len); sPacketHandler(&ddpPacketBuffer); release_mytm_mutex(); } else fdprintf("could not take mytm mutex - incoming packet dropped"); } } } return 0; }
int receive_one_request(t_trame *req, t_connections *cnt) { unsigned short i; while (42) { if (SDLNet_CheckSockets(cnt->sset, (unsigned int)-1) < 0) { fprintf(stderr, "SDLNet_CheckSockets: %s\n", SDLNet_GetError()); return (0); } for (i = 0; i < cnt->nb_clients; i++) { if (recv_trame(cnt, &(cnt->clients[i]), req)) { cnt->last_recv = &(cnt->clients[i]); return (1); } if (cnt->clients[i].loss > NET_MAXLOSS) return (0); } } // ne devrait pas en arriver jusque la: return (0); }
/** 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; } }
void NetworkCommandBuffer::Think() { SDLNet_SocketSet set; set = SDLNet_AllocSocketSet ( 1 ); if ( !set ) { RaiseSocketError ( "SDLNet_AllocSocketSet" ); } SocketSetEncapsulator free_on_quit ( set ); if ( SDLNet_TCP_AddSocket ( set, socket ) < 0 ) { RaiseSocketError ( "SDLNet_TCP_AddSocket" ); } int numready = SDLNet_CheckSockets ( set, 0 ); for ( ; numready == 1; numready = SDLNet_CheckSockets ( set, 0 ) ) { char msg; int nbread = SDLNet_TCP_Recv ( socket, &msg, 1 ); if ( nbread < 0 ) { RaiseSocketError ( "SDLNet_TCP_Recv: " ); } else if ( nbread == 0 ) { std::cout << "SDLNet_TCP_Recv: Unexpected read of size 0\n"; throw ReadSocketError(); } if ( debug_all_message ) { if ( msg < 32 ) std::cout << "Read: 0x" << ( int ) msg << "\n"; else std::cout << "Read: " << msg << "\n"; } if (current_command_size > 0) AddCharToBuffer ( msg ); else AddCharToCommandSize( msg ); } if ( numready < 0 ) { std::cout << "SDLNet_CheckSockets: " << SDLNet_GetError() << "\n"; perror ( "SDLNet_CheckSockets" ); throw ReadSocketError(); } }
Connection* Connection_create(const char* ip, Uint16 port) { Connection* self = (Connection*)calloc(1, sizeof(Connection)); if(!self) { return NULL; } if(SDLNet_ResolveHost(&self->address, ip, port)) { Connection_destroy(&self); return NULL; } if(!(self->socket = SDLNet_TCP_Open(&self->address))) { Connection_destroy(&self); return NULL; } if(!(self->socket_set = SDLNet_AllocSocketSet(1))) { Connection_destroy(&self); return NULL; } if(SDLNet_TCP_AddSocket(self->socket_set, self->socket) == -1) { Connection_destroy(&self); return NULL; } if(SDLNet_CheckSockets(self->socket_set, 5000) == 1) { Uint8 message = Connection_recv_flag(self); if(message == CONNECTED) { Uint8 buffer[6] = {0}; Connection_recv_data(self, buffer, 6); self->local_address.host = SDLNet_Read32(buffer); self->local_address.port = SDLNet_Read16(buffer + 4); printf("Successfully connected to server\n"); return self; } else if(message == FULL) { printf("Server is full\n"); } } else { printf("Server is not responding\n"); } Connection_destroy(&self); return NULL; }
void NetClient::update() { SDLNet_CheckSockets(socketset, 0); if (SDLNet_SocketReady(tcpsock)) { handleserver(); } }
/** * @brief Comprobador "Ready" * * @return Si todo está listo y correcto para la conexión, devolverá true. En caso contrario, devolverá false.s * * Comprueba que todo esté correcto para la conexión. */ bool CTcpSocket::Ready() const { bool rd = false; int numready = SDLNet_CheckSockets(set, 0); if (numready == -1) std::cerr << "SDLNet_CheckSockets: " << SDLNet_GetError() << std:: endl; else if (numready) rd = SDLNet_SocketReady (m_Socket); return rd; }
void I_WaitForPacket(int ms) { SDLNet_SocketSet ss = SDLNet_AllocSocketSet(1); SDLNet_UDP_AddSocket(ss, udp_socket); SDLNet_CheckSockets(ss,ms); SDLNet_FreeSocketSet(ss); #if (defined _WIN32 && !defined PRBOOM_SERVER) I_UpdateConsole(); #endif }
void connect(Uint16 port) { IPaddress ip; if(SDLNet_ResolveHost(&ip,NULL,port)==-1) { printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(1); } serversock = SDLNet_TCP_Open(&ip); if(!serversock) { printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError()); exit(2); } socketset = SDLNet_AllocSocketSet(32); if (!socketset) { printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError()); exit(1); //most of the time this is a major error, but do what you want. } SDLNet_TCP_AddSocket(socketset, serversock); while(true) { int num = 0; if ((num = SDLNet_CheckSockets(socketset, 10000)) == -1) { printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError()); //most of the time this is a system error, where perror might help you. perror("SDLNet_CheckSockets"); } else { accept_connections(); for(int i = 0; i < int(clients.size()); ++i) { if (clients[i]) clients[i]->update(); } for(int i = 0; i < int(clients.size()); ++i) { if (clients[i] && clients[i]->is_invalid()) { std::cout << "# client " << clients[i]->id << " got disconnected" << std::endl; SDLNet_TCP_DelSocket(socketset, clients[i]->tcpsock); SDLNet_TCP_Close(clients[i]->tcpsock); delete clients[i]; clients[i] = 0; } } } } }
// Transfer when current GB is using external clock // returns 1 if there is data to be recieved, 0 otherwise int transfer_ext(uint8_t data, uint8_t *recv) { #if !defined(PSP) && !defined(EMSCRIPTEN) && !defined(DREAMCAST) && !defined(THREE_DS) if ( (is_client || is_server) && (SDLNet_CheckSockets(socketset, 0) > 0) && (SDLNet_SocketReady(client) > 0)) { return !transfer(data, recv, 1); } #endif return 0; }
void I_WaitForPacket(int ms) { SDLNet_SocketSet ss = SDLNet_AllocSocketSet(1); SDLNet_UDP_AddSocket(ss, udp_socket); SDLNet_CheckSockets(ss,ms); SDLNet_FreeSocketSet(ss); // build script doesn't allow this //#if (defined _WIN32 && !defined PRBOOM_SERVER) // I_UpdateConsole(); //#endif }
void Peer::Update() { int toCheck = 0; if (sockets.size()) { toCheck = SDLNet_CheckSockets(watch, 0); // Print(toCheck); } if (toCheck) { for(auto & i: sockets) { if (SDLNet_SocketReady(i)) { UDPpacket * packet = SDLNet_AllocPacket(512); if (SDLNet_UDP_Recv(i, packet)) { if (packet != nullptr) { Print("PLEASE PROCESS THIS PACKET\n"); Print("%s:%s:%i %i\n", getIP(packet->address.host), std::to_string(SDLNet_Read16(&packet->address.port)), packet->channel, packet->data); // Print(getIP(packet->address.host), ":", std::to_string(SDLNet_Read16(&packet->address.port)), ":", packet->channel, packet->data); } } SDLNet_FreePacket(packet); } } } if (toCheck == -1) Print("toCheck getting errors in update\n"); /*if (bound) { UDPpacket *packet = SDLNet_AllocPacket(512); if (packet != nullptr) { int ans = SDLNet_UDP_Recv(sockets[0],packet); if (ans) { //TODO: add handling of sent time in packet //print(getIP(packet->address.host)<<":"<<std::to_string(SDLNet_Read16(packet->address.port))<<" ("<< packet->channel << "): " << packet->data); } else { if (ans == -1) { print("ERROR"); } } SDLNet_FreePacket(packet); } }//*/ }
connection receive_data(config& cfg, connection connection_num, bandwidth_in_ptr* bandwidth_in) { if(!socket_set) { return 0; } check_error(); if(disconnection_queue.empty() == false) { const network::connection sock = disconnection_queue.front(); disconnection_queue.pop_front(); throw error("",sock); } if(bad_sockets.count(connection_num) || bad_sockets.count(0)) { return 0; } if(sockets.empty()) { return 0; } const int res = SDLNet_CheckSockets(socket_set,0); for(std::set<network::connection>::iterator i = waiting_sockets.begin(); res != 0 && i != waiting_sockets.end(); ) { connection_details& details = get_connection_details(*i); const TCPsocket sock = details.sock; if(SDLNet_SocketReady(sock)) { // See if this socket is still waiting for it to be assigned its remote handle. // If it is, then the first 4 bytes must be the remote handle. if(is_pending_remote_handle(*i)) { union { char data[4] ALIGN_4; } buf; int len = SDLNet_TCP_Recv(sock,&buf,4); if(len != 4) { throw error("Remote host disconnected",*i); } const int remote_handle = SDLNet_Read32(&buf); set_remote_handle(*i,remote_handle); continue; } waiting_sockets.erase(i++); SDLNet_TCP_DelSocket(socket_set,sock); network_worker_pool::receive_data(sock); } else { ++i; } }
void BomberNetClient::sendDisconnection() { char data[7]; memset(data, 0, sizeof data); SDLNet_Write32(requestNumber, data); data[4] = 0x01; data[5] = GameConfig::Instance().getNbPlayerOfClient(); data[6] = '\0'; if (SDLNet_CheckSockets(BomberNetClient::socketset, 0) >= 0) { SDLNet_TCP_Send(BomberNetClient::tcpsock, &data, 7); requestNumber++; } }
connection accept_connection() { if(!server_socket) { return 0; } // A connection isn't considered 'accepted' until it has sent its initial handshake. // The initial handshake is a 4 byte value, which is 0 for a new connection, // or the handle of the connection if it's trying to recover a lost connection. /** * A list of all the sockets which have connected, * but haven't had their initial handshake received. */ static std::vector<TCPsocket> pending_sockets; static SDLNet_SocketSet pending_socket_set = 0; const TCPsocket sock = SDLNet_TCP_Accept(server_socket); if(sock) { DBG_NW << "received connection. Pending handshake...\n"; if(pending_socket_set == 0) { pending_socket_set = SDLNet_AllocSocketSet(32); } if(pending_socket_set != 0) { int res = SDLNet_TCP_AddSocket(pending_socket_set,sock); if (res != -1) { pending_sockets.push_back(sock); } else { ERR_NW << "Pending socket set is full! Disconnecting " << sock << " connection\n"; ERR_NW << "SDLNet_GetError() is " << SDLNet_GetError() << "\n"; SDLNet_TCP_Close(sock); } } else { ERR_NW << "Error in SDLNet_AllocSocketSet\n"; } } if(pending_socket_set == 0) { return 0; } const int set_res = SDLNet_CheckSockets(pending_socket_set,0); if(set_res <= 0) { return 0; } return accept_connection_pending(pending_sockets, pending_socket_set); }
void C_Server::UpdateClient() { m_numOfSocketsReady = SDLNet_CheckSockets(m_socketSet, 0); if(m_numOfSocketsReady == -1){ printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError()); //most of the time this is a system error, where perror might help you. perror("SDLNet_CheckSockets"); } else if(m_connected){ s_outPacket.m_playerCount = m_totalConnections; m_result = SDLNet_TCP_Send(m_clientSocket, &s_outPacket, sizeof(s_outPacket)); } std::cout << "bytes sent: " << (m_bytesSent += m_result) << std::endl; }
void NetServer::update() { SDLNet_CheckSockets(socketset, 0); if(SDLNet_SocketReady(tcpsock)) { handleserver(); } for(int i = 0; i < MAXCLIENTS; ++i) { if(SDLNet_SocketReady(clients[i].sock)) { handleclient(i); } } }
int Connection::checkSet(int timeout){ ScopedMutexLock(pimpl_->dataAccess); if( pimpl_->group != NULL ){ int num = SDLNet_CheckSockets(pimpl_->group, timeout); if( num == -1 ){ pimpl_->active = false; pimpl_->connectTime = 0; } else { pimpl_->active = true; } return num; } return -2; // not in set }
//Reads Received data from server,if any, to this->buffer, returns true if new data has arrived, else false bool NetworkClient::ReadReceivedDataToBuffer() { int socketactive = SDLNet_CheckSockets(this->sockets, 0); if(socketactive != 0) //Current socket is alive { socketactive = SDLNet_SocketReady(this->clientsocket); if(socketactive != 0) //Current socket got message from server? { //int responsebytes = //SDLNetTCPRecv returns response in bytes, int SDLNet_TCP_Recv(this->clientsocket, buffer, BUFFERSIZE); return true; } } return false; }
Bits TCPClientSocket::GetcharNonBlock() { // return: // -1: no data // -2: socket closed // 0..255: data if(SDLNet_CheckSockets(listensocketset,0)) { Bitu retval =0; if(SDLNet_TCP_Recv(mysock, &retval, 1)!=1) { isopen=false; return -2; } else return retval; } else return -1; }
void ServerConnection::update() { if (!tcpsock) return; int num = 0; if ((num = SDLNet_CheckSockets(socketset, 0)) == -1) { printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError()); //most of the time this is a system error, where perror might help you. perror("SDLNet_CheckSockets"); } if (num > 0) { if (SDLNet_SocketReady(tcpsock)) { const int MAXLEN = 1024; int result; char msg[MAXLEN]; result = SDLNet_TCP_Recv(tcpsock, msg, MAXLEN); if(result <= 0) { // TCP Connection is broken. (because of error or closure) SDLNet_TCP_Close(tcpsock); exit(1); } else { for(int i = 0; i < result; ++i) { if (msg[i] == '\n') { process_command(buffer); //std::cout << server_buffer << std::endl; buffer.clear(); } else { buffer += msg[i]; } } } } } }
/*! * Main loop of the lan protocol service */ void serve_clients_lan_protocol (global_status_type * global_status, global_option_type * global_option) { init_frame_status (global_status, global_option); for (;;) { int number_ready_socket; #if defined(DEBUG) fprintf (stderr, "Waiting for status packets for frame %u\n", global_status->frame_number); #endif number_ready_socket = SDLNet_CheckSockets (global_status->server_socket_set, SERVER_SOCKET_TIMEOUT); if (number_ready_socket == -1) { fprintf (stderr, "Error in socket waiting (disconnection ?).\n"); break; } if (number_ready_socket == 1) { #if defined(DEBUG) fprintf (stderr, "Got a packet\n"); #endif /* We're awaiting a packet in the server socket */ if (read_incoming_server_packet (global_status)) { /* Stores the incoming status and updates clients status accordingly */ store_remote_status_lan (global_status, global_option); /* Sends packet (if needed) to client accordingly to their status */ send_digest_lan_packets (global_status, global_option); } } } }