void ngl_net_close_client(char num) { if (num==0) { SDLNet_TCP_Close(csd0); quit=1; waiting0=1; reading0=0; printf("\nDesconectado el 0\n"); } if (num==1) { SDLNet_TCP_Close(csd1); waiting1=1; reading1=0; printf("\nDesconectado el 1\n"); } if (num==2) { SDLNet_TCP_Close(csd1); waiting2=1; reading2=0; printf("\nDesconectado el 2\n"); } }
/* add a client into our array of clients */ Client *add_client(TCPsocket sock, char *name) { fix_nick(name); if(!strlen(name)) { putMsg(sock,"Invalid Nickname...bye bye!"); SDLNet_TCP_Close(sock); return(NULL); } if(!unique_nick(name)) { putMsg(sock,"Duplicate Nickname...bye bye!"); SDLNet_TCP_Close(sock); return(NULL); } clients=(Client*)realloc(clients, (num_clients+1)*sizeof(Client)); clients[num_clients].name=name; clients[num_clients].sock=sock; num_clients++; /* server side info */ printf("--> %s\n",name); /* inform all clients, including the new one, of the joined user */ send_all(mformat("ss","--> ",name)); return(&clients[num_clients-1]); }
/*接続*/ void connection_connect(CONNECTION_DATA* con){ /*変数宣言*/ TCPsocket *sock = &con->socket; char* str; int content_length = -1; int is_err = false; FILE* log_file; /*接続先IPを取得*/ con->ip = SDLNet_TCP_GetPeerAddress(*sock); /*ビジー状態に設定*/ if(!lock_connection(con)){ SDLNet_TCP_Close(*sock); return; } /*ヘッダを判断する*/ str = NetUtl_readLine(sock); if(str == null){ /*通信終わり*/ SDLNet_TCP_Close(*sock); /*接続終了フラグ*/ unlock_connection(con); return; } if(strncmp(str,POST_HEADER,strlen(POST_HEADER)) != 0){ is_err = true; } /*とりあえず最後まで受信する。*/ if(is_err){//エラー /*ログに追加*/ log_file = lock_log_file(); time_output(); ip_output(con->ip); fprintf(log_file,"%s\n",str); unlock_log_file(); //最後まで受信するだけ while(*(str = NetUtl_readLine(sock)) != END_CHAR){ } }else{//ヘッダを取得する while(*(str = NetUtl_readLine(sock)) != END_CHAR){ if(content_length < 0){ if(strncmp( str, CONTENT_LENGTH_HEADER, strlen(CONTENT_LENGTH_HEADER) ) == 0){ sscanf(str,CONTENT_LENGTH_HEADER_F,&content_length); } }//else if(){} } } if(!is_err && content_length >= 0){/*とりあえず通信するに値する*/ connection_do_request(con,content_length); }else{/*まったく関係ない*/ connection_send_error(sock); } /*通信終わり*/ SDLNet_TCP_Close(*sock); /*接続終了フラグ*/ unlock_connection(con); }
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 * 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; }
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; } } } }
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); } } } }
void Server::Shutdown(){ // send shutdown message for (map<int, PlayerObject*>::iterator j = playerObjects.begin(); j != playerObjects.end(); ++j){ sprintf(outgoing, "4\n"); SDLNet_TCP_Send(client_data[j->first].socket, outgoing, 17); } // clean up playerObjects.clear(); gameObjects.clear(); // close socket SDLNet_TCP_Close(server_socket); // destroy renderer SDL_DestroyRenderer(renderer); renderer = NULL; // close window SDL_DestroyWindow(window); window = NULL; // shutdown sdlnet SDLNet_Quit(); // shutdown sdl SDL_Quit(); }
/** * @brief Destructor * * Si #m_Socket no es nulo, se liberará el espacio en memoria que ocupa la estructura. * Además, se libera el espacio que ocupa el conjunto #set y cierra el socket m_Socket. */ CTcpSocket::~CTcpSocket() { if (!(m_Socket == NULL)) { SDLNet_TCP_DelSocket(set,m_Socket); SDLNet_FreeSocketSet(set); SDLNet_TCP_Close (m_Socket); } }
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; }
void wait_for_greenlight() { struct NetPacket pkt; int i; printf("CLIENT: Waiting for greenlight...\n"); do { int rc; while ((rc = grabPacket(sock, socketset, &pkt)) == 0) { SDL_Delay(100); /* nap and then try again. */ } if (rc < 0) { printf("CLIENT: Lost connection.\n"); SDLNet_TCP_Close(sock); exit(42); } } while (pkt.cmd != NETCMD_GREENLIGHT); printf("CLIENT: Got greenlight.\n"); for (i = 0; i < JNB_MAX_PLAYERS; i++) { if (pkt.arg & (1 << i)) { printf("CLIENT: There is a player #%d.\n", i); player[i].enabled = 1; } } }
//************************************************************************** //* 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) } } } }
ClientConnection::~ClientConnection() { // Signal to stop status = -1; SDL_WaitThread(send_thread, NULL); // We don't need to lock because the send_thread is terminated while (data_to_send.size() > 0) { delete data_to_send.front().data; data_to_send.pop_front(); } // make sure we don't trash messages when killing the thread. SDL_LockMutex(messages_mutex); SDL_KillThread(recieve_thread); SDL_UnlockMutex(messages_mutex); SDLNet_TCP_Close(socket); SDL_DestroyMutex(send_mutex); SDL_DestroyMutex(messages_mutex); // Remove this client from the world //entity->world->delete_entity(entity); //entity = 0; }
int main(int argc, char **argv) { SDL_Rect pos; t_world new_world; t_bag new_bag; SDLNet_SocketSet set; if (signal(SIGINT, free_all) == SIG_ERR) exit(EXIT_FAILURE); if (argc != 3) write(2, USAGE, strlen(USAGE)); else { init_buf_msg(&(gl_screen.my_msg)); gl_screen.info_bag = &new_bag; gl_screen.pos = &pos; gl_screen.world = &new_world; init_screen(&gl_screen); init_net(argv[1], (unsigned)atoi(argv[2]), &set, &gl_screen); init_sdl(&gl_screen); events(&gl_screen, &set); SDLNet_FreeSocketSet(set); SDLNet_TCP_Close(gl_screen.sock_server); free_gui(&gl_screen); } return (EXIT_SUCCESS); }
void new_connection(TCPsocket sock) { TCPsocket tmp; struct socket_node *socket; IPaddress *ip; /* accept the connection temporarily */ tmp = SDLNet_TCP_Accept(sock); if (!tmp) do_error(SDLNet_GetError()); /* are we full or game already started? */ if (get_active_players() + 1 > NUM_PLAYERS || current_turn) SDLNet_TCP_Close(tmp); else { /* nope! */ socket = new_socket(SOCKET_CLIENT); socket->sock = tmp; if (SDLNet_TCP_AddSocket(sockset, tmp) < 0) do_error(SDLNet_GetError()); ip = SDLNet_TCP_GetPeerAddress(tmp); if (!ip) do_error(SDLNet_GetError()); if (SDLNet_ResolveIP(ip)) strcpy(socket->host, SDLNet_ResolveIP(ip)); else sprintf(socket->host, "Unknown IP"); join_player(socket); /* add player to game */ } }
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 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 Connection::clean(){ ScopedMutexLock(pimpl_->dataAccess); --pimpl_->refCount; if( pimpl_->refCount == 0 ){ if( pimpl_->group != NULL ){ if( pimpl_->userSocket ){ SDLNet_TCP_DelSocket(pimpl_->group, pimpl_->userSocket); } if( pimpl_->createdSet ){ SDLNet_FreeSocketSet(pimpl_->group); pimpl_->createdSet = 0; } pimpl_->group = NULL; } if( pimpl_->userSocket != NULL ){ SDLNet_TCP_Close( pimpl_->userSocket ); pimpl_->userSocket = NULL; } pimpl_->peer = NULL; pimpl_->active = false; pimpl_->connectTime = 0; delete pimpl_; } pimpl_ = NULL; }
int serverRecvPacket(struct NetPacket* pkt) { int rc; int i; assert(is_server); for (i = 0; i < JNB_MAX_PLAYERS; i++) { TCPsocket s = net_info[i].sock; if ((i == client_player_num) || (!player[i].enabled)) continue; rc = grabPacket(s, net_info[i].socketset, pkt); if (rc < 0) { //struct NetPacket pkt; player[i].enabled = 0; SDLNet_TCP_Close(s); pkt->cmd = NETCMD_BYE; pkt->arg = i; pkt->arg2 = 0; pkt->arg3 = 0; pkt->arg4 = 0; sendPacketToAll(pkt); } else if (rc > 0) { return(i); /* it's all good. */ } } return(-1); /* no packets available currently. */ }
int Connection::connect(const std::string &host, int port){ if( (port == 0) || isSpace(host) ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "Connection::connect(string, int): Port can't be 0. Host can't be whitespace." << std::endl; return -1; } IPaddress ip; if( SDLNet_ResolveHost(&ip, host.c_str(), port) == -1 ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl; return -1; } ScopedMutexLock(pimpl_->dataAccess); //make sure is dissconected if( pimpl_->userSocket != NULL ){ SDLNet_TCP_Close( pimpl_->userSocket ); pimpl_->userSocket = NULL; } pimpl_->userSocket = SDLNet_TCP_Open(&ip); if( pimpl_->userSocket == NULL ){ std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl; pimpl_->active = false; pimpl_->connectTime = 0; return -1; } pimpl_->peer = SDLNet_TCP_GetPeerAddress(pimpl_->userSocket); pimpl_->active = true; pimpl_->connectTime = SDL_GetTicks(); return 1; }
void Server::CloseConnection(void) { IteratoreLista it; TCPsocket curr; for(it=this->connessioni.begin(); it!=this->connessioni.end(); it++){ if((*it).first!=0){ curr=(*it).second.connessione; SDLNet_TCP_Close(curr); curr=NULL; (*it).second.exit=true; SDL_WaitThread((*it).second.id_thread,NULL); this->connessioni.erase(it); } } SDLNet_TCP_Close(this->server); this->server=NULL; }
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; } } }
int main(int argc, char **argv) { IPaddress ip; /* Server address */ TCPsocket sd; /* Socket descriptor */ int quit, len; char buffer[512]; /* Simple parameter checking */ if (argc < 3) { fprintf(stderr, "Usage: %s host port\n", argv[0]); exit(EXIT_FAILURE); } if (SDLNet_Init() < 0) { fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } /* Resolve the host we are connecting to */ if (SDLNet_ResolveHost(&ip, argv[1], atoi(argv[2])) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } /* Open a connection with the IP provided (listen on the host's port) */ if (!(sd = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } /* Send messages */ quit = 0; while (!quit) { printf("Write something:\n>"); scanf("%s", buffer); len = strlen(buffer) + 1; if (SDLNet_TCP_Send(sd, (void *)buffer, len) < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if(strcmp(buffer, "exit") == 0) quit = 1; if(strcmp(buffer, "quit") == 0) quit = 1; } SDLNet_TCP_Close(sd); SDLNet_Quit(); return EXIT_SUCCESS; }
/** * exit rocsmq system */ int rocsmq_exit (TCPsocket sock) { /* * todo: verbindung abbauen */ SDLNet_TCP_Close(sock); SDLNet_Quit(); return 0; }
NetworkThread::~NetworkThread() { // TODO: close all client sockets delete clientSocketList; SDLNet_TCP_Close(sd); SDLNet_Quit(); }
void closeServer() { SDLNet_Quit(); SDLNet_TCP_Close(TCPsock); SDLNet_UDP_Close(udpSendSock); SDLNet_UDP_Close(udpRecvSock); SDL_Quit(); IMG_Quit(); }
CIncomingConnectionListener::~CIncomingConnectionListener() { if( m_listeningSocketSet ) { m_listeningSocketSet->delSocketFromSet(m_listeningSocket); SDLNet_TCP_Close(m_listeningSocket); } }
void NetworkClient::Exit() { SDLNet_FreeSocketSet(this->sockets); SDLNet_TCP_Close(this->clientsocket); delete []host; //delete []isSocketFree; //delete []clientsocket; }
C_Server::~C_Server() { if(m_serverActive){ SDLNet_TCP_Close(m_clientSocket); SDLNet_Quit(); //close } }