// send a string buffer over a TCP socket with error checking // returns 0 on any errors, length sent on success int putMsg(TCPsocket sock, char *buf) { Uint32 len,result; if(!buf || !strlen(buf)) return(1); // determine the length of the string len=strlen(buf)+1; // add one for the terminating NULL // change endianness to network order len=SDL_SwapBE32(len); // send the length of the string result=SDLNet_TCP_Send(sock,&len,sizeof(len)); if(result<sizeof(len)) { if(SDLNet_GetError() && strlen(SDLNet_GetError())) // sometimes blank! printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); return(0); } // revert to our local byte order len=SDL_SwapBE32(len); // send the buffer, with the NULL as well result=SDLNet_TCP_Send(sock,buf,len); if(result<len) { if(SDLNet_GetError() && strlen(SDLNet_GetError())) // sometimes blank! printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); return(0); } // return the length sent return(result); }
void TCPConnectionServer::Send( std::string str, int connectionNr ) { if ( !isSocketConnected[ connectionNr ] ) { std::cout << "TCPConnection.cpp@" << __LINE__ << " Error! Not connected " << std::endl; return; } void* messageData = ConvertStringToVoidPtr(str); int messageSize = static_cast< int > ( str.length() ); int bytesSent = 0; if ( isServer ) { bytesSent = SDLNet_TCP_Send( serverSocket[connectionNr], messageData, messageSize); } else { bytesSent = SDLNet_TCP_Send( tcpSocket, messageData, messageSize); } if ( bytesSent < messageSize ) { std::cout << "TCPConnection.cpp@" << __LINE__ << " Send failed : " << SDLNet_GetError() << std::endl; isSocketConnected[connectionNr] = false; } }
//************************************************************************** //* MODE 3 Lobby Screen * //************************************************************************** static void checkMouseMode3(SDL_Event *event, SDL_Point *currentMouseLocation, SDL_Rect buttonPlacement[], int *select, int *mode, int modeMaxButtons[], bool *match, int *keyboardMode){ for(int i=0; i < modeMaxButtons[3]; i++){ if(mouseOnButton(currentMouseLocation, buttonPlacement, &i)){ // Is the mouse on button 'i' ? if(event->type == SDL_MOUSEBUTTONDOWN){ *keyboardMode = ENTERING_TEXT; if(i == 2){ // Ready //playerReady = !playerReady; SDLNet_TCP_Send(client.TCPSock, "#", strlen("#")); } else if(i == 1){ // Leave isConnected = false; SDLNet_TCP_Send(client.TCPSock, "-", strlen("-")); SDLNet_TCP_Close(client.TCPSock); SDLNet_UDP_Close(client.UDPRecvSock); SDLNet_UDP_Close(client.UDPSendSock); for(int i=0; i < MAX_PLAYERS; i++) playerReady[i] = 0; clearTextStrings(6); printf("LEFT; '-' sent to server, socket closed, ready statuses cleared, textstrings cleared, mode changed\n"); //***************************************** *mode = 5; } // (ELSE: Enter Chat Message Window Pressed) } } } }
void NetworkCommandBuffer::SendString ( const std::string message ) { char buffer[4]; SDLNet_Write32(message.size(), buffer); SDLNet_TCP_Send ( socket, buffer, 4 ); SDLNet_TCP_Send ( socket, const_cast<char*> ( message.data() ), message.size() ); }
void NetServer::handleserver() { int which; unsigned char data; TCPsocket newsock = SDLNet_TCP_Accept(tcpsock); if (newsock == NULL) return; /* Look for unconnected person slot */ for (which = 0; which < MAXCLIENTS; ++which) { if (!clients[which].sock) { break; } } if (which == MAXCLIENTS) { /* Look for inactive person slot */ for (which = 0; which < MAXCLIENTS; ++which) { if (clients[which].sock && !clients[which].active) { /* Kick them out.. */ data = NET_MSG_REJECT; SDLNet_TCP_Send(clients[which].sock, &data, 1); SDLNet_TCP_DelSocket(socketset, clients[which].sock); SDLNet_TCP_Close(clients[which].sock); numclients--; #ifdef _DEBUG printf("Killed inactive socket %d\n", which); #endif break; } } } if (which == MAXCLIENTS) { /* No more room... */ data = NET_MSG_REJECT; SDLNet_TCP_Send(newsock, &data, 1); SDLNet_TCP_Close(newsock); #ifdef _DEBUG printf("Connection refused -- server full\n"); #endif } else { /* Add socket as an inactive person */ clients[which].sock = newsock; clients[which].peer = *SDLNet_TCP_GetPeerAddress(newsock); SDLNet_TCP_AddSocket(socketset, clients[which].sock); numclients++; #ifdef _DEBUG printf("New inactive socket %d\n", which); #endif } }
void HandleServer(void) { TCPsocket newsock; int which; unsigned char data; newsock = SDLNet_TCP_Accept(servsock); if ( newsock == NULL ) { return; } /* Look for unconnected person slot */ for ( which=0; which<CHAT_MAXPEOPLE; ++which ) { if ( ! people[which].sock ) { break; } } if ( which == CHAT_MAXPEOPLE ) { /* Look for inactive person slot */ for ( which=0; which<CHAT_MAXPEOPLE; ++which ) { if ( people[which].sock && ! people[which].active ) { /* Kick them out.. */ data = CHAT_BYE; SDLNet_TCP_Send(people[which].sock, &data, 1); SDLNet_TCP_DelSocket(socketset, people[which].sock); SDLNet_TCP_Close(people[which].sock); #ifdef DEBUG fprintf(stderr, "Killed inactive socket %d\n", which); #endif break; } } } if ( which == CHAT_MAXPEOPLE ) { /* No more room... */ data = CHAT_BYE; SDLNet_TCP_Send(newsock, &data, 1); SDLNet_TCP_Close(newsock); #ifdef DEBUG fprintf(stderr, "Connection refused -- chat room full\n"); #endif } else { /* Add socket as an inactive person */ people[which].sock = newsock; people[which].peer = *SDLNet_TCP_GetPeerAddress(newsock); SDLNet_TCP_AddSocket(socketset, people[which].sock); #ifdef DEBUG fprintf(stderr, "New inactive socket %d\n", which); #endif } }
void send( TCPsocket* sock, char type, const void* data, char len, bool outputAllowed ) { if ( *sock != NULL ) { IPaddress * clientIP = SDLNet_TCP_GetPeerAddress(*sock); if (outputAllowed) printf("Sending -> %s : (%c:%X) \"%s\"\n", getStringAddress(*clientIP), type, type, data); SDLNet_TCP_Send(*sock, &type,1); SDLNet_TCP_Send(*sock, &len, 1); SDLNet_TCP_Send(*sock, data, len); } }
bool CDataSocket::flush() { if (!m_socket) { CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlError, _("Attempt to write to not initialized data socket.\n")); return true; } if( time(NULL) - m_lastPong > LOST_CONNECTION_TIME ) { m_lastPong = time(NULL); CLog::instance()->log(CLog::msgFlagNetwork,CLog::msgLvlInfo,_("(%s:%d) : Ping timeout.\n"),m_remoteHost.c_str(),m_remotePort); m_outputBuffer.clear(); return false; } // if it's time to send ping insert dummy packet into output buffer if( !m_outputBuffer.size() && (time(NULL) - m_lastPing > PING_TIME) ) m_outputBuffer.push_back(CData()); m_lastPing = time(NULL); std::vector<CData>::iterator i; for(i = m_outputBuffer.begin(); i != m_outputBuffer.end(); i++ ) { if( (*i).length() > SOCK_BUFFER_SIZE ) { CLog::instance()->log(CLog::msgLvlError,_("Data too long (%d).\n"),(*i).length()); continue; }; netPacketSize dataLength = (netPacketSize)(*i).length(); if ( SDLNet_TCP_Send(m_socket, &dataLength, sizeof(netPacketSize)) <= 0 ) { CLog::instance()->log(CLog::msgFlagNetwork,CLog::msgLvlInfo,_("(%s:%d) : Error occured while writing socket.\n"), m_remoteHost.c_str(), m_remotePort); m_sockErrorOccured = true; m_outputBuffer.clear(); return false; } if( dataLength ) if( SDLNet_TCP_Send(m_socket, (char*)(*i).data(), dataLength ) <= 0 ) { CLog::instance()->log(CLog::msgFlagNetwork,CLog::msgLvlInfo,_("(%s:%d) : Error occured while writing socket.\n"), m_remoteHost.c_str(), m_remotePort); m_sockErrorOccured = true; m_outputBuffer.clear(); return false; } } m_outputBuffer.clear(); return true; }
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); } } }
void IRCLobby::sendIRCLine(const std::string& line) { if(SDLNet_TCP_Send(irc_server_socket, const_cast<char*> (line.c_str()), line.size()) != (int) line.size()) throw Exception("Error when sending irc message '%s': %s", line.c_str(), SDLNet_GetError()); #ifndef WITHOUT_NETPANZER LOGGER.debug("sending irc:%s",line.c_str()); #endif static char lf[]="\n"; if(SDLNet_TCP_Send(irc_server_socket,lf,1) != 1) throw Exception("Error when sending irc lf: %s", SDLNet_GetError()); }
void * main_thread(void * data) { int flag=1,choice,n; int temp; TCPsocket client_socket,server_socket; if(!intialize_thread()) { printf("\n Therer is some error while initializing thread"); return 0; } printf("\n Value of active ports is:%d",get_active_threads()); // first server receive request from client to connect and open master server socket. To be created only once.-permanent if(common_connect_server(&host_ipaddress,&server_socket,global_port,(const char *)NULL)==0) return (void *)1; while(quit) { // Open client socket on server side for sending dynamic port address-temprary if((client_socket=SDLNet_TCP_Accept(server_socket))) { // send port address to client pthread_mutex_lock(&mutex_variable); printf("\n Value of active ports:%d",get_active_threads()); if(get_active_threads()==0) { int temp=0; SDLNet_TCP_Send(client_socket,&(temp),2); SDLNet_TCP_Close(client_socket); pthread_mutex_unlock(&mutex_variable); } else if(SDLNet_TCP_Send(client_socket,&(thread_header->client.port),2)==2) { printf("\nNew Port is send to client"); // close temprary client socket SDLNet_TCP_Close(client_socket); // opening port so that server can accept content from client in different thread; pthread_mutex_unlock(&mutex_variable); printf("\n Activating thread"); activate_thread(); } } } printf("\nEverything is OK now exiting"); SDLNet_TCP_Close(server_socket); cleanup_thread(); return NULL; }
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 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 network_tcp_send(TCPsocket tcp, const void* data, int len) { int r = SDLNet_TCP_Send(tcp, data, len); if (r < len) { std::cerr << "Failed to send full data over TCP: " << SDLNet_GetError() << "\n"; } return r; }
void MySocketConnection::write(const std::vector<unsigned char>& bytes, int length) { int result = SDLNet_TCP_Send(this->socket, &bytes[0], length); // _LOGDATA("Socket data send"); if (result < length) { throw WAException(std::string(SDLNet_GetError()), WAException::SOCKET_EX, WAException::SOCKET_EX_SEND); } }
void ServerConnection::send(const std::string& str) { if (tcpsock) { int result = SDLNet_TCP_Send(tcpsock, const_cast<char*>(str.c_str()), str.length()); if(result < int(str.length())) { printf( "SDLNet_TCP_Send: %s\n", SDLNet_GetError() ); // It may be good to disconnect sock because it is likely invalid now. } } else { // Not connected, so directly procses the command without a // round trip through the server std::string tmp; for(std::string::size_type i = 0; i < str.length(); ++i) { if (str[i] == '\n') { process_command("client 0 " + tmp); tmp.clear(); } else tmp += str[i]; } } }
void ServerConnection::connect(const char* hostname, Uint16 port) { IPaddress ip; if(SDLNet_ResolveHost(&ip, hostname, port) == -1) { printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(1); } tcpsock = SDLNet_TCP_Open(&ip); if(!tcpsock) { printf("SDLNet_TCP_Open: %s %s:%d\n", SDLNet_GetError(), hostname, port); exit(2); } else { std::string line = "client_version 1\n"; SDLNet_TCP_Send(tcpsock, const_cast<char*>(line.c_str()), line.length()); socketset = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketset, tcpsock); } }
// Send a string over TCP/IP int send_message(std::string msg, TCPsocket sock) { char * buff = (char *)msg.c_str(); SDLNet_TCP_Send(sock, buff, MAXLEN); return 1; }
void CServer::Send(Sint16 a, bool b) { /*int result; int b = a; int len=sizeof(b); result = SDLNet_TCP_Send (client, &b, sizeof(int)); if (result<len) { printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); }*/ int result; int x[2]; x[0] = a; x[1] = b; int len=sizeof(x); result = SDLNet_TCP_Send (client, &x, sizeof(x)); if (result<len) { printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); } }
int player_hit(struct player *p, struct game *g) { if (player_remove(p, g)) { ERR_TRACE(); return -1; } if (!p->lives) { player_respawn(p); if (player_add(p, g)) { ERR_TRACE(); return -1; } } else { if (!--p->lives) { SDLNet_TCP_Send(p->client->s, "\11", 1); player_free(p); } else { player_respawn(p); if (player_add(p, g)) { ERR_TRACE(); return -1; } } } return 0; }
int ClientConnection::send_thread_func() { while (status == 0) { // Remove a packet from the queue or wait SDL_LockMutex(send_mutex); if (data_to_send.size() > 0) { int len = data_to_send.front().len; char * data = data_to_send.front().data; data_to_send.pop_front(); SDL_UnlockMutex(send_mutex); // Send the packet int result = SDLNet_TCP_Send(socket, data, len); delete data; if (result < len) { printf("%s:%d SDLNet_TCP_Send: %s\n", __FILE__, __LINE__, SDLNet_GetError()); // It may be good to disconnect sock because it is likely invalid now. status = -1; return 0; // terminate thread } } else { SDL_UnlockMutex(send_mutex); SDL_Delay(0); } } return 0; }
bool TCPClientSocket::Putchar(Bit8u data) { if(SDLNet_TCP_Send(mysock, &data, 1)!=1) { isopen=false; return false; } return true; }
void TCPConnection::SendPackets() { while( !close_thread_ ) { if( !packet_queue_.empty() ) { queue_mtx_.lock(); // remove the packet form the queue std::unique_ptr<BasePacket> packet = std::move( packet_queue_.front() ); packet_queue_.pop(); queue_mtx_.unlock(); // send the front packet if( SDLNet_TCP_Send( socket_, packet->Data(), packet->Size() ) < (int)packet->Size() ) { // something terrible went wrong connection_good_ = false; } } } std::cout << "TCP thread closed" << std::endl; }
int TCP_RECEIVEOBJ::start_watching(void) { if (sock) { clear_buffer(); sprintf(writebuf,"watch %d\n",streamnum); if (SDLNet_TCP_Send(sock, writebuf, strlen(writebuf))==strlen(writebuf)) { read_tcp(watchbuf, 6); if (!strcmp(watchbuf,"200 OK")) { watching=TRUE; cout << "start watching.\n"; packetcount=0;bufstart=0; bufend=0; QueryPerformanceCounter((_LARGE_INTEGER *)×tamp); return(200); } } SDLNet_TCP_Close(sock); sock=0; } watching=FALSE; /* if (hDlg==ghWndToolbox) { close_toolbox(); actobject=this; make_dialog(); }*/ return(0); }
void TCP_RECEIVEOBJ::reset(void) { /* int x; for (x=0;x<MAX_CONNECTS;x++) { out[x].from_port=-1; out[x].to_port=-1; out[x].to_object=-1; } for (x=0;x<MAX_PORTS;x++) { out_ports[x].out_name[0]=0; strcpy(out_ports[x].out_dim,"none"); strcpy(out_ports[x].out_desc,"none"); out_ports[x].out_min=-1.0f; out_ports[x].out_max=1.0f; } outports=0; inports=0; height=50; */ if (sock) { clear_buffer(); strcpy(writebuf,"close\n"); SDLNet_TCP_Send(sock, writebuf, strlen(writebuf)); SDLNet_TCP_Close(sock); sock=0; cout << "closed.\n"; } streamnum=-1; watching=false; }
int Connection::send(const inp::INFPacket& data){ // prepare packet for sending PacketList packList; splitForSend(data, packList); // if there is nothing to send, leave. if( packList.empty() ){ return 1; } ScopedMutexLock(pimpl_->dataAccess); if( pimpl_->userSocket != NULL ){ // Send packets in list for(size_t i = 0; i < packList.size(); ++i ){ if( !packList[i].empty() ){ //check if everything went through if( SDLNet_TCP_Send( pimpl_->userSocket, &packList[i][0], packList[i].size() ) < packList[i].size() ) { SDLNet_TCP_Close( pimpl_->userSocket ); pimpl_->userSocket = NULL; pimpl_->peer = NULL; pimpl_->active = false; pimpl_->connectTime = 0; pimpl_->lastSent.clear(); return -1; } } } pimpl_->lastSent = packList; } else { pimpl_->connectTime = 0; return -1; } return 1; }
static void comms_write_message(int type, _u8 data) { #ifndef HAVE_LIBSDL_NET return; #else _u8 msg[2]; if (sock == NULL) { /* XXX: warn? */ return; } #ifdef COMMS_DEBUG if (type == COMMS_DATA) printf("wrote byte %02x\n", data); #endif msg[0] = type; msg[1] = data; if (SDLNet_TCP_Send(sock, msg, 2) != 2) { printf("write error on socket: %s\n", SDLNet_GetError()); comms_shutdown(); } #endif /* HAVE_LIBSDL_NET */ }
struct game *network_create_game(struct network *n, FILE *f) { struct game *g = game_load_level(f); if (!g) { return 0; } g->ident = rand(); printf("%i\n",g->ident); g->n = n; uint8_t name_len = 0; if (g->name) name_len = strlen(g->name); char *data = malloc(6 + name_len); *data = 5; *(data + 1) = name_len; *(uint32_t *)(data + 2) = htonl(g->ident); memcpy(data+6,g->name,name_len); SDL_mutexP(n->m);//can fail linkedlist_add_last(n->games,g); linkedlist_node *nn = n->users->first; for (;nn;nn = nn->next) { struct network_client *nc = nn->data; SDLNet_TCP_Send(nc->s, data, name_len + 6); } SDL_mutexV(n->m); free(data); return g; }
bool TCPClientSocket::SendArray(Bit8u* data, Bitu bufsize) { if(SDLNet_TCP_Send(mysock, data, bufsize)!=bufsize) { isopen=false; return false; } return true; }
int net_http_get(char* out, int max, char* fmt, ...) { va_list args; va_start(args, fmt); vsnprintf(url_buffer, 500, fmt, args); va_end(args); int parts = sscanf(url_buffer, "http://%[^/]%s", host_buffer, path_buffer); if (parts != 2) { warning("Couldn't resolve parts of URL '%s'", url_buffer); return HTTP_ERR_URL; } IPaddress ip; if ( SDLNet_ResolveHost(&ip, host_buffer, 80) == -1) { warning("Couldn't Resolve Host: %s", SDLNet_GetError()); return HTTP_ERR_HOST; } TCPsocket sock = SDLNet_TCP_Open(&ip); if(!sock) { warning("Couldn't open socket: %s", SDLNet_GetError()); return HTTP_ERR_SOCKET; } char sockout[1024*4]; snprintf(sockout,(1024*4-1), "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "\r\n", path_buffer, host_buffer); int result = SDLNet_TCP_Send(sock, sockout, strlen(sockout)); if (result < strlen(sockout)) { warning("Error sending http request: %s", SDLNet_GetError()); return HTTP_ERR_DATA; } char line[1024]; bool header = true; strcpy(out, ""); while (SDLNet_TCP_RecvLine(sock, line, 1023)) { /* TODO: Check against max arg */ if (header) { if (strcmp(line, "\r\n") == 0) { header = false; } } else { strcat(out, line); } } return HTTP_ERR_NONE; }