void MoodBoxServer::getNextArtmessageAndReport(Callback callback, QVariant state, qint32 previousMessageId)
{
    send(callback, state, new GetNextArtmessageAndReport(previousMessageId));
}
Beispiel #2
0
void * server_thread(void* arg)
{
  int sockfd,new_fd; //socket file dscriptor, vraci funkce int socket()
  struct sockaddr_in my_addr;    // my address information
  struct sockaddr_in newHostAdr; // connector's address information
  unsigned int sin_size;
  int yes = 1;//????
  int retval;

  sockfd = socket(PF_INET, SOCK_STREAM, 0); // do some error checking!
  // nastaveni socketu, tak aby pri znovu spusteni programu program nekleknul
  if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) 
  {
   perror("setsockopt");
   exit(1);
  }

  // nastaveni struktury my_addr
  my_addr.sin_family = AF_INET;         // host byte order
  my_addr.sin_port = htons(MYPORT);     // short, network byte order
  my_addr.sin_addr.s_addr = INADDR_ANY; // auto-fill with my IP
  memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct

  // sváže socket se jménem tedy se my_addr
  retval = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
  if (retval != 0) { perror("bind"); exit(1); }

  const char *msg = "Zdravi Vas DC servo regulator\nZadejte otacky \n";
  // nastaveni socketu do rezimu cekani, funkce se okamzite vraci
  retval = listen(sockfd, BACKLOG);  // backlog nastavuje kolik max. pripojeni
  if (retval != 0) { perror("listen"); exit(1); }

  // nekonecna smycka ktera ceka na pripojeni uzivatele, jakmile se pripoji
  // obsluhuje ho a az se odpoji ceka na dlasiho
while(1){
  printf("Server ceka az se pripoji klient....\n");
  fflush(stdout);

  // pripojovani prvniho ucastnika
  sin_size = sizeof(struct sockaddr_in);
  new_fd = accept(sockfd, (struct sockaddr *)&newHostAdr, &sin_size);
  if (new_fd < 0){ perror("accept"); exit(1);}
  
  // prepsani globalni promenne ze klient je pripojen
  pthread_mutex_lock(&mutex_isClientConnected); 
   isClientConnected = TRUE;  
  pthread_mutex_unlock(&mutex_isClientConnected); 

  printf("Klient se pripojil od %s:%d\n", inet_ntoa(newHostAdr.sin_addr), ntohs(newHostAdr.sin_port));
  fflush(stdout); 
  send(new_fd, msg, strlen(msg), 0); // posli uvitaci zpravu

  // zalozeni vlakna, ID clienta se predava jako parametr
  pthread_t  recieverThread;
  pthread_create(&recieverThread, NULL, server_reciever_thread , (void**)new_fd);

// nekonecna smycka, pravidelne odesila klientu zpravu o stavu,
// vypisuje na servru aktualni stav, ceka jestli v mainu se to neukoncilo
// ceka jestli se klient neodpojil
  while(1)
  {
   // pole pro jednotlive retezce ktere se nakonec slepi a odeslou
   char strPozadovaneOtacky[200];
   char strAktualniOtacky[200];
   char strSmer[200];

   // nacteni pozadovanych otacek
   pthread_mutex_lock(&mutex_demandRotates); 
    sprintf(strPozadovaneOtacky,"%d",demandRotates); 
   pthread_mutex_unlock(&mutex_demandRotates); 

   // nacteni aktualnich otacek
   pthread_mutex_lock(&mutex_aktualRotates); 
    sprintf(strAktualniOtacky,"%d",aktualRotates); 
   pthread_mutex_unlock(&mutex_aktualRotates); 

   // ncteni aktualniho smeru
   pthread_mutex_lock(&mutex_rotatesDirection); 
    if(rotatesDirection==TRUE) strcpy(strSmer,"vlevo");
    else strcpy(strSmer,"vpravo");
   pthread_mutex_unlock(&mutex_rotatesDirection); 

   // vytvoreni retezce
   char msg[500];
   // inicializace retezce
   for(int i =0;i<sizeof(msg);i++)
   {
     msg[i] =0; 
   } 

   // slepeni retezcu
   strcat(msg,"\rPozadovane ");
   strcat(msg,strPozadovaneOtacky);
   strcat(msg," Aktualni ");
   strcat(msg,strAktualniOtacky);
   strcat(msg," Smer ");
   strcat(msg,strSmer);
   
   // zarpvnani retezce
   for(int i=strlen(msg);i<50;i++)
   {
     msg[i] = ' ';
   } 
    msg[49] = 0;

   // odeslani retezce
   send(new_fd, msg, strlen(msg), 0); // posli uvitaci zpravu

   //kontrola zda klient neni odpojen
   pthread_mutex_lock(&mutex_isClientConnected); 
    if(isClientConnected==FALSE)
    {
     // oznameni na serveru ze se klient odpojil 
     printf("Klient se odpojil \n");
     fflush(stdout);
     pthread_mutex_unlock(&mutex_isClientConnected); 
     // ukonceni vlakna
     pthread_join(recieverThread,NULL);
     close(new_fd);  // uzavreni socketu 
     break;
    }
   pthread_mutex_unlock(&mutex_isClientConnected); 

   // kontrola zda program neni j*z ukoncen
   pthread_mutex_lock(&mutex_endOfTheProgam); 
   if(endOfTheProgram == TRUE)
   {
     // musi se zajistit to ze prijmaci vlakno zrovna
     // nema zadnej mutex
     pthread_mutex_lock(&mutex_demandRotates); 
      //ukonceni vlakna
      pthread_cancel(recieverThread);
     pthread_mutex_unlock(&mutex_demandRotates); 
     pthread_mutex_unlock(&mutex_endOfTheProgam);
     return NULL;
   }
   pthread_mutex_unlock(&mutex_endOfTheProgam); 

   usleep(200000);// cekani 200ms
  } // konec smycky obsluhy klineta

}// konec smycky pripojovani a obsluhy klinta  

return NULL;
}
Beispiel #3
0
int32_t Connection::onEvents(const Event& event)
{
    int32_t result = E_ERROR;
    int32_t retcode = E_ERROR;
    uint32_t events = event.events;
#ifdef DEBUG_TRACE/*{{{*/
    std::cout << "#[Connection::OnEvents] sockfd["
        << sockfd_.sockfd()
        << "], state["
        << state()
        << "]"
        << std::endl;
#endif // DEBUG_TRACE/*}}}*/
    if (LISTEN == state()) {
        if (EPOLLIN & events) {/*{{{*/
            if (S_SUCCESS != (retcode = accept())) {
                event_handler_->onAcceptFailed(this);
                result = retcode;
                goto ExitError;
            }
        } else {
            event_handler_->onError(this);
            disconnect();
            goto ExitError;
        }/*}}}*/
    } else if (CONNECT_SENT == state()) {
        if (!sockfd_.isError() && ((EPOLLIN & events) || (EPOLLOUT & events))) {/*{{{*/
            set_state(ESTABLISHED);
            event_handler_->onConnectEstablished(this);
        } else {
            event_handler_->onConnectFailed(this);
            disconnect();
            goto ExitError;
        }/*}}}*/
    } else if (ESTABLISHED == state()) {
        if (EPOLLIN & events) {/*{{{*/
            recv();
            retcode = event_handler_->onRead(this);
        }
        if (EPOLLOUT & events) {
            retcode = event_handler_->onWrite(this);
            send();
        }
        if (EPOLLPRI & events) {
            retcode = event_handler_->onPrimaryData(this);
        }
        if (EPOLLERR & events) {
            retcode = event_handler_->onError(this);
            recv();
            goto ExitError;
        }
        if (EPOLLHUP & events) {
            retcode = event_handler_->onHup(this);
            recv();
            goto ExitError;
        }/*}}}*/
    } else {
        goto ExitOK;
    }

ExitOK:
    result = S_SUCCESS;
ExitError:
    if (CLOSE_WAIT == state()) {
        event_handler_->onClose(this);
        disconnect();
    }
    return result;
}
Beispiel #4
0
/**F*****************************************************************/
void cmd (SOCKET s)
{
    SECURITY_ATTRIBUTES sa;
    PROCESS_INFORMATION pi;
    STARTUPINFO         si;
    OVERLAPPED          lap;

    HANDLE              lh[4];
    DWORD               p, e, wr;
    BYTE                buf[BUFSIZ];
    int                 len;
    HANDLE              evt[MAXIMUM_WAIT_OBJECTS];
    DWORD               evt_cnt=0, sck_evt=0;
    DWORD               stdout_evt=0, proc_evt=0;

    // create event for socket
    evt[sck_evt = evt_cnt++] = WSACreateEvent();

    // initialize security descriptor
    sa.nLength              = sizeof (SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle       = TRUE;

    // create anonymous read/write pipes for stdin of cmd.exe
    if (CreatePipe (&lh[0], &lh[1], &sa, 0))
    {
        // format named pipe using tick count and current process id
        wnsprintf ((char*)buf, BUFSIZ, "\\\\.\\pipe\\%08X",
                   GetCurrentProcessId() ^ GetTickCount());

        // create named pipe for stdout/stderr of cmd.exe
        lh[2] = CreateNamedPipe ((char*)buf,
                                 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                                 PIPE_TYPE_BYTE     | PIPE_READMODE_BYTE | PIPE_WAIT,
                                 PIPE_UNLIMITED_INSTANCES, 0, 0, 0, NULL);

        if (lh[2] != INVALID_HANDLE_VALUE)
        {
            // open the pipe
            lh[3] = CreateFile ((char*)buf, MAXIMUM_ALLOWED,
                                0, &sa, OPEN_EXISTING, 0, NULL);

            if (lh[3] != INVALID_HANDLE_VALUE)
            {
                // create event for stdout handle of cmd.exe
                // initially in a signalled state
                evt[evt_cnt]=CreateEvent (NULL, TRUE, TRUE, NULL);
                stdout_evt = evt_cnt++;

                // zero initialize parameters for CreateProcess
                ZeroMemory (&si, sizeof (si));
                ZeroMemory (&pi, sizeof (pi));

                si.cb              = sizeof (si);
                si.hStdInput       = lh[0];  // assign the anon read pipe
                si.hStdError       = lh[3];  // assign the named write pipe
                si.hStdOutput      = lh[3];  //
                si.dwFlags         = STARTF_USESTDHANDLES;

                // execute cmd.exe with no window
                if (CreateProcess (NULL, "cmd", NULL, NULL, TRUE,
                                   CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
                {
                    // monitor state of cmd.exe
                    evt[proc_evt = evt_cnt++] = pi.hProcess;

                    ZeroMemory (&lap, sizeof (lap));
                    // assign stdout event
                    lap.hEvent = evt[stdout_evt];

                    // set pending to 0
                    p=0;

                    for (;;)
                    {
                        // wait for events on cmd.exe and socket
                        e=wait_evt(evt, evt_cnt, sck_evt, s);

                        // cmd.exe ended?
                        if (e==proc_evt) {
                            break;
                        }

                        // wait failed?
                        if (e == -1) {
                            break;
                        }
                        // is this socket event?
                        if (e == sck_evt)
                        {
                            // receive data from socket
                            len=recv (s, (char*)buf, sizeof(buf), 0);
                            if (len<=0) break;

                            // write to stdin of cmd.exe
                            WriteFile (lh[1], buf, len, &wr, 0);
                        } else

                            // output from cmd.exe?
                            if (e == stdout_evt)
                            {
                                // if not in pending read state, read stdin
                                if (p == 0)
                                {
                                    ReadFile (lh[2], buf, sizeof(buf),
                                              (LPDWORD)&len, &lap);
                                    p++;
                                } else {
                                    // get overlapped result
                                    if (!GetOverlappedResult (lh[2], &lap,
                                                              (LPDWORD)&len, FALSE)) {
                                        break;
                                    }
                                }
                                // if we have something
                                if (len != 0)
                                {
                                    // send to remote
                                    len=send (s, (char*)buf, len, 0);
                                    if (len<=0) break;
                                    p--;
                                }
                            }
                    }
                    // end cmd.exe incase it's still running
                    TerminateProcess (pi.hProcess, 0);
                    // close handles and decrease events
                    CloseHandle (pi.hThread);
                    CloseHandle (pi.hProcess);
                    evt_cnt--;
                }
                // close handle to named pipe for stdout
                CloseHandle (lh[3]);
            }
            // close named pipe for stdout
            CloseHandle (lh[2]);
        }
        // close anon pipes for read/write to stdin
        CloseHandle (lh[1]);
        CloseHandle (lh[0]);
    }
    // close stdout event handle
    CloseHandle (evt[stdout_evt]);
    evt_cnt--;
    // close socket event handle
    CloseHandle (evt[sck_evt]);
    evt_cnt--;
}
Beispiel #5
0
/*
 * Set the date in the machines controlled by timedaemons by communicating the
 * new date to the local timedaemon.  If the timedaemon is in the master state,
 * it performs the correction on all slaves.  If it is in the slave state, it
 * notifies the master that a correction is needed.
 * Returns 0 on success.  Returns > 0 on failure, setting retval to 2;
 */
int
netsettime(time_t tval)
{
	struct timeval tout;
	struct servent *sp;
	struct tsp msg;
	struct sockaddr_in lsin, dest, from;
	fd_set ready;
	long waittime;
	int s, port, timed_ack, found, lerr;
	socklen_t length;
	char hostname[MAXHOSTNAMELEN];

	if ((sp = getservbyname("timed", "udp")) == NULL) {
		warnx("timed/udp: unknown service");
		return (retval = 2);
	}

	dest.sin_port = sp->s_port;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = htonl((u_long)INADDR_ANY);
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0) {
		if (errno != EAFNOSUPPORT)
			warn("timed");
		return (retval = 2);
	}

	memset(&lsin, 0, sizeof(lsin));
	lsin.sin_family = AF_INET;
	for (port = IPPORT_RESERVED - 1; port > IPPORT_RESERVED / 2; port--) {
		lsin.sin_port = htons((u_short)port);
		if (bind(s, (struct sockaddr *)&lsin, sizeof(lsin)) >= 0)
			break;
		if (errno == EADDRINUSE)
			continue;
		if (errno != EADDRNOTAVAIL)
			warn("bind");
		goto bad;
	}
	if (port == IPPORT_RESERVED / 2) {
		warnx("all ports in use");
		goto bad;
	}
	memset(&msg, 0, sizeof(msg));
	msg.tsp_type = TSP_SETDATE;
	msg.tsp_vers = TSPVERSION;
	if (gethostname(hostname, sizeof(hostname))) {
		warn("gethostname");
		goto bad;
	}
	(void)strlcpy(msg.tsp_name, hostname, sizeof(msg.tsp_name));
	msg.tsp_seq = htons((u_short)0);
	msg.tsp_time.tv_sec = htonl((u_long)tval);
	msg.tsp_time.tv_usec = htonl((u_long)0);
	length = sizeof(struct sockaddr_in);
	if (connect(s, (struct sockaddr *)&dest, length) < 0) {
		warn("connect");
		goto bad;
	}
	if (send(s, (char *)&msg, sizeof(struct tsp), 0) < 0) {
		if (errno != ECONNREFUSED)
			warn("send");
		goto bad;
	}

	timed_ack = -1;
	waittime = WAITACK;
loop:
	tout.tv_sec = waittime;
	tout.tv_usec = 0;

	FD_ZERO(&ready);
	FD_SET(s, &ready);
	found = select(FD_SETSIZE, &ready, (fd_set *)0, (fd_set *)0, &tout);

	length = sizeof(lerr);
	if (!getsockopt(s,
	    SOL_SOCKET, SO_ERROR, (char *)&lerr, &length) && lerr) {
		if (lerr != ECONNREFUSED)
			warnc(lerr, "send (delayed error)");
		goto bad;
	}

	if (found > 0 && FD_ISSET(s, &ready)) {
		length = sizeof(struct sockaddr_in);
		if (recvfrom(s, &msg, sizeof(struct tsp), 0,
		    (struct sockaddr *)&from, &length) < 0) {
			if (errno != ECONNREFUSED)
				warn("recvfrom");
			goto bad;
		}
		msg.tsp_seq = ntohs(msg.tsp_seq);
		msg.tsp_time.tv_sec = ntohl(msg.tsp_time.tv_sec);
		msg.tsp_time.tv_usec = ntohl(msg.tsp_time.tv_usec);
		switch (msg.tsp_type) {
		case TSP_ACK:
			timed_ack = TSP_ACK;
			waittime = WAITDATEACK;
			goto loop;
		case TSP_DATEACK:
			(void)close(s);
			return (0);
		default:
			warnx("wrong ack received from timed: %s",
			    tsptype[msg.tsp_type]);
			timed_ack = -1;
			break;
		}
	}
	if (timed_ack == -1)
		warnx("can't reach time daemon, time set locally");

bad:
	(void)close(s);
	return (retval = 2);
}
Beispiel #6
0
int main(void)
{
  int sockfd, numbytes;
  char buf[MAXDATASIZE];
  struct addrinfo hints, *servinfo, *p;
  int rv;
  char s[INET6_ADDRSTRLEN];
//print local IP and port number
    struct sockaddr_in PatientSock;
    int PatientSockLen;
    //char ipstr[INET6_ADDRSTRLEN]="nunki.usc.edu";
    char ipstr[INET6_ADDRSTRLEN]="localhost";
    struct hostent *he;
    struct in_addr **addr_list;
    int i;
    int getsock_check;
    struct sockaddr_in my_addr;
    int addrlen=sizeof(struct sockaddr);
    char destiaddr[20]="127.0.0.1";
//read patient1.txt
  FILE *file_1;
  char patient1[2][20];
//send file
  char head[50]="authenticate ";
//compare receive
  char com[MAXDATASIZE]={'f','a','i','l','u','r','e','\0'};
//send availble
    char avail[15]={'a','v','a','i','l','a','b','l','e','\0'};
//receive table and print;receive patient key board input; send number
    char availtable[200];
    int availtablelen;
    int appointnum[1];// only for now
    char appointcom[10];//to transform int to char
    int j,k;
    char *availabilities[6][3];
    int printnum;//to check whether all availabilities are stored fully
    char selectmes[15];
//whether successfully booked
    char reserved[15];
    int docportnum;
//test side
   
    
//  if (argc != 2) {
 // fprintf(stderr,"usage: client hostname\n");
 // exit(1);
 // }

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
    //hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
    
// the IP address of server should be hard coded into the program; change before submit!!!!!!!!!!
  if ((rv = getaddrinfo(destiaddr, PORT, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }
// loop through all the results and connect to the first we can
  for(p = servinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype,
			 p->ai_protocol)) == -1) {
      perror("client: socket");
      continue;
    }
    if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("client: connect");
      continue;
    }
    break;
  }
  if (p == NULL) {
    fprintf(stderr, "client: failed to connect\n");
    return 2;
  }
//inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s);
//printf("client: connecting to %s\n", s);
    
    
//host name should be hardcode in the program; change before submit!!!!!!
   // gethostname(ipstr, sizeof ipstr);
    he=gethostbyname(ipstr);
  //  getsockname(sockfd, (struct sockaddr *)&PatientSock, &PatientSockLen);
//from description checking!!!!!!!!!!
    //Retrieve the locally-­‐bound name of the specified socket and store it in the sockaddr structure
    getsock_check=getsockname(sockfd,(struct sockaddr *)&my_addr, (socklen_t *)&addrlen);
    //Error checking
    if(getsock_check==-1)
    {
        perror("getsockname");
        exit(1);
    }
    printf("Phase 1: Patient 1 has TCP port number %d and IP address ", ntohs(my_addr.sin_port));
//BJ P73
  //printf("Patient 1 has TCP port number %d and IP address ", ntohs(PatientSock.sin_port));
  addr_list = (struct in_addr **)he->h_addr_list;
  for(i = 0; addr_list[i] != NULL; i++) {
    printf("%s ", inet_ntoa(*addr_list[i]));
  }
  printf("\n");

  freeaddrinfo(servinfo); // all done with this structure
    
//read patient1.txt and send
  file_1=fopen("patient1.txt","r");
  fscanf(file_1,"%s",patient1[0]);
  fscanf(file_1,"%s",patient1[1]);
  fclose(file_1);
  strcat(head,patient1[0]);
  strcat(head," ");
  strcat(head,patient1[1]);
  if (send(sockfd, head, 50, 0) == -1)
    perror("send");
  else
    printf("Phase 1: Authentication requst from Patient 1 with username %s and password %s has been sent to the Health Center Server\n",patient1[0],patient1[1]);
//authenticate successful or not

  if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
    perror("recv");
    exit(1);
  }

  buf[numbytes] = '\0';
  printf("Phase 1: Patient 1 authentication result: %s\n",buf);
 
  
   if(strcmp(buf,com)==0)
    {
  //    printf("dead\n");
      close(sockfd);
      exit(1);
    }
   
  printf("Phase 1: End of Phase 1 for Patient1\n");

// Phase 2!!!!!
//send "available"
    if (send(sockfd, avail, 15, 0) == -1)
        perror("send");
//receive table
    if ((availtablelen = recv(sockfd, availtable, 200, 0)) == -1) {
        perror("recv");
        exit(1);
    }
    avail[availtablelen] = '\0';
//store what you receive
    //strtok(availtable," ");
    for(j=0;j<6;j++)
    {
        for(k=0;k<3;k++)
        {
            if (j==0&&k==0) {
                availabilities[j][k]=strtok(availtable," ");
            }
            else
            {
                if((availabilities[j][k]=strtok(NULL," "))==NULL)
                {
                   // printnum=5;
                    continue;
                }
            }
            //fscanf(file_2,"%s", availabilities[i][j]);
            //  availabilities[i][5][0]=1;//right?
        }
    }
    //need to check whether the last line of availabilities[j][k] is null!
    if (availabilities[5][0]==NULL) {
        printnum=5;
        availabilities[5][0]="-1";//to assign this line as useless
    }
    else
    {
        printnum=6;
    }
//print the table;receive patient key board input; send number
    printf("Phase 2: The following appointments are available for Patient1:\n");
    for(j=0;j<printnum;j++)
    {
        for(k=0;k<3;k++)
        {

            printf("%s ", availabilities[j][k]);
        }
        printf("\n");
    }
    //printf("\n");
    printf("Please enter the preferred appointment index and press enter:\n");
    scanf("%d",&appointnum[0]);//is error check needed here?!!!!!!!!!
    //error check
    sprintf(appointcom,"%d",appointnum[0]);
    while((strcmp(availabilities[0][0],appointcom))&&(strcmp(availabilities[1][0],appointcom))&&(strcmp(availabilities[2][0],appointcom))&&(strcmp(availabilities[3][0],appointcom))&&(strcmp(availabilities[4][0],appointcom))&&(strcmp(availabilities[5][0],appointcom))){
        printf("Please enter the preferred appointment index and press enter:\n");
        scanf("%d",&appointnum[0]);
        sprintf(appointcom,"%d",appointnum[0]);
    }
    //send select message
    strcpy(selectmes, "selection ");
    strcat(selectmes,appointcom);
    if (send(sockfd, selectmes, 15, 0) == -1)
        perror("send");
    //receive reply whether the patient book is accepted
    if ((recv(sockfd, reserved, 15, 0)) == -1) {
        perror("recv");
        exit(1);
    }
    char *docname;
    char *docport;
    if(strcmp(reserved,"notavailable")){
        docname=strtok(reserved," ");// the doctor's name could be stored here
        docport=strtok(NULL," ");
        docportnum=atoi(docport);
        printf("Phase 2: The requested appointment is available and reserved to Patient1. The assigned doctor port number is %d\n",docportnum);
    //end of patient tcp progress
        close(sockfd);
    }
    else{
        printf("Phase 2: The requested appointment from Patient 1 is not available.Exiting...\n");
        close(sockfd);
        exit(1);
    }
    
    //from now on start the phase 3 udp!!!!! 11.9
    int sockfd_1;
    struct addrinfo hints_1, *servinfo_1, *p_1;
    int rv_1;
    int numbytes_1;
    //read patient1insurance.txt
    FILE *file_3;
    char patient1insurance[20];
    // receive price
    socklen_t addr_len_1;
    struct sockaddr_storage their_addr_1;
    char price[3];
    
  //  if (argc != 2) {
   //     fprintf(stderr,"usage: talker hostname message\n");
    //    exit(1);
   // }
    memset(&hints_1, 0, sizeof hints_1);
    hints_1.ai_family = AF_UNSPEC;
    hints_1.ai_socktype = SOCK_DGRAM;
    if ((rv_1 = getaddrinfo(destiaddr, docport, &hints_1, &servinfo_1)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv_1));
        return 1;
    }
    // loop through all the results and make a socket
    for(p_1 = servinfo_1; p_1 != NULL; p_1 = p_1->ai_next) {
        if ((sockfd_1 = socket(p_1->ai_family, p_1->ai_socktype,
                             p_1->ai_protocol)) == -1) {
            perror("talker: socket");
            continue;
        }
        break;
    }
    if (p_1 == NULL) {
        fprintf(stderr, "talker: failed to bind socket\n");
        return 2;
    }
    //screen
    
    
    
    // printf("Phase 3: Patient 1 has a dynamic UDP port number and IP address\n");//handle!!!!!!!!
    
    
    //read patient1insurance.txt
    file_3=fopen("patient1insurance.txt","r");
    fscanf(file_3,"%s",patient1insurance);
    // fscanf(file_1,"%s",patient1[1]);
    fclose(file_3);
    
    if ((numbytes_1 = sendto(sockfd_1, patient1insurance, strlen(patient1insurance), 0,p_1->ai_addr, p_1->ai_addrlen)) == -1) {
        perror("talker: sendto");
        exit(1);
    }
    // IP address and port number
    char hostname[20]="localhost";
    struct hostent *ipaddress;
    struct sockaddr_in my_addr_1;
    int addrlen_1=sizeof(struct sockaddr);
    struct in_addr **addr_list_1;
    ipaddress=gethostbyname(hostname);//IP address
    addr_list_1 = (struct in_addr **)ipaddress->h_addr_list;
    getsockname(sockfd_1,(struct sockaddr *)&my_addr_1, (socklen_t *)&addrlen_1);//socket
    printf("Phase 3: Patient 1 has a dynamic UDP port %d and IP address %s\n",ntohs(my_addr_1.sin_port), inet_ntoa(*addr_list_1[0]));
    // get the Ip address of doc
  
    addr_len_1=sizeof(struct sockaddr);
    printf("Phase 3: The cost estimation request from Patient 1 with insurance plan %s has been sent to the doctor with port number %s and IP adress ", patient1insurance, docport);
    // receive price
    if ((numbytes_1 = recvfrom(sockfd_1, price, 3 , 0,
                             (struct sockaddr *)&their_addr_1, &addr_len_1)) == -1) {
        perror("recvfrom");
        exit(1);
    }
    
   // struct sockaddr_in peer_addr;
    int addrlen_2=sizeof(struct sockaddr);
    struct sockaddr_in *peer_addrt=(struct sockaddr_in *)&their_addr_1;
    char peer_IP[INET6_ADDRSTRLEN];
    inet_ntop(AF_INET,&peer_addrt->sin_addr,peer_IP,sizeof peer_IP);
    printf("%s\n",peer_IP);//Print IP address
    
    
    printf("Phase 3: Patient 1 receives %s$ estimation cost from doctor with port number %s and name %s \n",price,docport, docname);
    //  printf("Phase 3: Patient 1 receives %s$ estimation cost from doctor with port number and name %s \n",price, docname);
    //printf("%s\n",price);
    printf("Phase 3: End of Phase 3 for Patient 1\n");
    freeaddrinfo(servinfo_1);
    // printf("talker: sent %d bytes to %s\n", numbytes, argv[1]);
    close(sockfd_1);
    return 0;

    
    
    
    
    //end of patient program
  return 0;
}
/* connects to a host on a specified tcp port, sends a string, and gets a
	 response. loops on select-recv until timeout or eof to get all of a
	 multi-packet answer */
int
process_tcp_request2 (const char *server_address, int server_port,
	const char *send_buffer, char *recv_buffer, int recv_size)
{

	int result;
	int send_result;
	int recv_result;
	int sd;
	struct timeval tv;
	fd_set readfds;
	int recv_length = 0;

	result = np_net_connect (server_address, server_port, &sd, IPPROTO_TCP);
	if (result != STATE_OK)
		return STATE_CRITICAL;

	send_result = send (sd, send_buffer, strlen (send_buffer), 0);
	if (send_result<0 || (size_t)send_result!=strlen(send_buffer)) {
		printf ("%s\n", _("Send failed"));
		result = STATE_WARNING;
	}

	while (1) {
		/* wait up to the number of seconds for socket timeout
		   minus one for data from the host */
		tv.tv_sec = socket_timeout - 1;
		tv.tv_usec = 0;
		FD_ZERO (&readfds);
		FD_SET (sd, &readfds);
		select (sd + 1, &readfds, NULL, NULL, &tv);

		/* make sure some data has arrived */
		if (!FD_ISSET (sd, &readfds)) {	/* it hasn't */
			if (!recv_length) {
				strcpy (recv_buffer, "");
				printf ("%s\n", _("No data was received from host!"));
				result = STATE_WARNING;
			}
			else {										/* this one failed, but previous ones worked */
				recv_buffer[recv_length] = 0;
			}
			break;
		}
		else {											/* it has */
			recv_result =
				recv (sd, recv_buffer + recv_length,
					(size_t)recv_size - recv_length - 1, 0);
			if (recv_result == -1) {
				/* recv failed, bail out */
				strcpy (recv_buffer + recv_length, "");
				result = STATE_WARNING;
				break;
			}
			else if (recv_result == 0) {
				/* end of file ? */
				recv_buffer[recv_length] = 0;
				break;
			}
			else {										/* we got data! */
				recv_length += recv_result;
				if (recv_length >= recv_size - 1) {
					/* buffer full, we're done */
					recv_buffer[recv_size - 1] = 0;
					break;
				}
			}
		}
		/* end if(!FD_ISSET(sd,&readfds)) */
	}
	/* end while(1) */

	close (sd);
	return result;
}
void MoodBoxServer::getNotifications(Callback callback, QVariant state, QString key, qint64 packetId)
{
    send(callback, state, new GetNotifications(key, packetId));
}
void MoodBoxServer::getNotificationTimeout(Callback callback, QVariant state)
{
    send(callback, state, GetNotificationTimeout::___new_());
}
void MoodBoxServer::notificationRegister(Callback callback, QVariant state)
{
    send(callback, state, NotificationRegister::___new_());
}
void MoodBoxServer::notificationUnregister(Callback callback, QVariant state, QString key)
{
    send(callback, state, new NotificationUnregister(key));
}
void MoodBoxServer::deleteMoodstrip(Callback callback, QVariant state, qint32 moodstripId)
{
    send(callback, state, new DeleteMoodstrip(moodstripId));
}
void MoodBoxServer::addPictureToMoodstrip(Callback callback, QVariant state, qint32 moodstripId, qint32 messageId, QString author, QByteArray data, QString contentType, bool isLast)
{
    send(callback, state, new AddPictureToMoodstrip(moodstripId, messageId, author, data, contentType, isLast));
}
void MoodBoxServer::createMoodstrip(Callback callback, QVariant state, QString caption, bool isHidden, qint32 channelId)
{
    send(callback, state, new CreateMoodstrip(caption, isHidden, channelId));
}
void MoodBoxServer::deleteMessage(Callback callback, QVariant state, qint32 contactId, MessageType::MessageTypeEnum messageType, qint32 messageId)
{
    send(callback, state, new DeleteMessage(contactId, messageType, messageId));
}
void MoodBoxServer::searchChannel(Callback callback, QVariant state, qint32 pageNumber, qint32 recordsPerPage, QString value)
{
    send(callback, state, new SearchChannel(pageNumber, recordsPerPage, value));
}
void MoodBoxServer::checkInvitation(Callback callback, QVariant state, QString code)
{
    send(callback, state, new CheckInvitation(code));
}
void MoodBoxServer::getChannelInfo(Callback callback, QVariant state, qint32 channelId)
{
    send(callback, state, new GetChannelInfo(channelId));
}
Beispiel #19
0
int
main(int argc, char **argv)
{
  char inpstr[2000], authstr[2000];
  char buffer[1000], *miasma;
  char *next, *current;
  int len, i, ret;
  int host_socket;
  fd_set readmask;
  pid_t ident_pid;

  printf("*** ArIdent Daemon Version 2.0.2\n*** Forking...\n");

  /* not even think in turning this into a switch. Been there, done that. */
  ret = (int) fork();
  if (ret == -1) { exit(1);  }
  if (ret !=  0) { _exit(0); }

  setsid();
  if (argc) {
    /* make it look pwetty */
    sprintf(argv[0], "[ArIdent Daemon for %s]", TALKERNAME);
  }
  host_socket = socket_connect(SERVER, HOSTPORT);
  if (host_socket < 0) {
    printf("Error in socket_connect() to %s:%s.\n", SERVER, HOSTPORT);
    exit(0);
  }
  authenticate_host(host_socket);
  ident_pid = getpid();
  printf("*** Booted successfully with PID %d ***\n", ident_pid);
  for (;;) {
    FD_ZERO(&readmask);
    FD_SET(host_socket, &readmask);
    len = select(1 + host_socket, &readmask, NULL, NULL, NULL);
    if (len == -1) {
      continue;
    }
    len = recv(host_socket, inpstr, (sizeof inpstr) - 3, 0);
    if (!len) {
#ifdef DEBUG
      printf("Disconnected from host.\n");
#endif
      shutdown(host_socket, SHUT_WR);
      close(host_socket);
      host_socket = -1;
      do {
        sleep(5);
        host_socket = socket_connect(SERVER, HOSTPORT);
      } while (host_socket < 0);
      authenticate_host(host_socket);
      continue;
    }
    inpstr[len] = '\0';
    inpstr[len + 1] = 127;
#ifdef DEBUG
    printf("RECEIVED: %s\n", inpstr);
#endif
    next = inpstr - 1;
    while (*(++next) != 127) {
      current = next;
      while (*next && *next != '\n') {
        ++next;
      }
      *next = '\0';
      if (!strncmp(current, "EXIT", 4)) {
        shutdown(host_socket, SHUT_WR);
        close(host_socket);
        exit(0);
      }
      switch (double_fork()) {
      case -1:
        exit(1);                /* fork failure */
      case 0:
        break;                  /* child continues */
      default:
        continue;               /* parent carries on the fine family tradition */
      }
      if (argc) {
        sprintf(argv[0], "[ArIdent Child for %s]", TALKERNAME);
      }
      if (!strncmp(current, "PID", 3)) {
        sprintf(buffer, "PRETURN: %u\n", ident_pid);
#ifdef DEBUG
        printf("[PID] %s\n", buffer);
#endif
        send(host_socket, buffer, strlen(buffer), 0);
        _exit(0);
      }
      if (!strncmp(current, "SITE:", 5)) {
        /* They want a site. So call the site function and send a message back. */
        miasma = current + 6;
        sprintf(buffer, "RETURN: %s %s\n", miasma, get_proc(miasma));
#ifdef DEBUG
        printf("[SITE] %s\n", buffer);
#endif
        send(host_socket, buffer, strlen(buffer), 0);
        _exit(0);
      }
      if (!strncmp(current, "AUTH:", 5)) {
        char word[MAX_WORDS + 1][WORD_LEN + 1];
        struct timeval t_struct;
        int auth_socket;

        /* They want a username. So setup nice sockets stuff. */
        miasma = current + 6;
        wordfind(miasma, word);
        miasma = strchr(word[3], '!');
        if (miasma) {
          *miasma = '\0';
        }
        auth_socket = socket_connect(word[3], "113");
        if (auth_socket < 0) {
          _exit(0);
        }
        sprintf(buffer, "%s, %s\n", word[1], word[2]);
        send(auth_socket, buffer, strlen(buffer), 0);
        for (;;) {
          FD_ZERO(&readmask);
          FD_SET(auth_socket, &readmask);
          t_struct.tv_sec = 10;
          t_struct.tv_usec = 0;
          len = select(1 + auth_socket, &readmask, NULL, NULL, &t_struct);
          if (len == -1) {
            continue;
          }
          if (!len) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          len = recv(auth_socket, authstr, (sizeof authstr) - 3, 0);
          if (!len) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          if (len > 255 || len < 5) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          authstr[len] = '\0';  /* Find the last "word" in inpstr. */
          if (strstr(authstr, "ERROR")) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          for (i = len - 1; i > 2; --i) {
            if (authstr[i] == ' ' || authstr[i] == ':') {
              miasma = authstr + i + 1;
              sprintf(buffer, "ARETURN: %s %s %s\n", word[1],
                      word[0], miasma);
#ifdef DEBUG
              printf("[AUTH] %s\n", buffer);
#endif
              send(host_socket, buffer, strlen(buffer), 0);
              shutdown(auth_socket, SHUT_WR);
              close(auth_socket);
              _exit(0);
            }
          }
          shutdown(auth_socket, SHUT_WR);
          close(auth_socket);
          _exit(0);
        }
      }
      _exit(0);
    }
  }
  return 0;
}
void MoodBoxServer::sendChannelMessage(Callback callback, QVariant state, qint32 channelId, QByteArray message, QString metadata)
{
    send(callback, state, new SendChannelMessage(channelId, message, metadata));
}
/*
 *	exscan_intra
 *
 *	Function:	- basic exscan operation
 *	Accepts:	- same arguments as MPI_Exscan()
 *	Returns:	- MPI_SUCCESS or error code
 */
int
mca_coll_basic_exscan_intra(void *sbuf, void *rbuf, int count,
                            struct ompi_datatype_t *dtype,
                            struct ompi_op_t *op,
                            struct ompi_communicator_t *comm,
                            mca_coll_base_module_t *module)
{
    int size, rank, err;
    ptrdiff_t true_lb, true_extent, lb, extent;
    char *free_buffer = NULL;
    char *reduce_buffer = NULL;

    rank = ompi_comm_rank(comm);
    size = ompi_comm_size(comm);

    /* For MPI_IN_PLACE, just adjust send buffer to point to
     * receive buffer. */
    if (MPI_IN_PLACE == sbuf) {
        sbuf = rbuf;
    }

    /* If we're rank 0, then just send our sbuf to the next rank, and
     * we are done. */
    if (0 == rank) {
        return MCA_PML_CALL(send(sbuf, count, dtype, rank + 1,
                                 MCA_COLL_BASE_TAG_EXSCAN,
                                 MCA_PML_BASE_SEND_STANDARD, comm));
    }

    /* If we're the last rank, then just receive the result from the
     * prior rank, and we are done. */
    else if ((size - 1) == rank) {
        return MCA_PML_CALL(recv(rbuf, count, dtype, rank - 1,
                                 MCA_COLL_BASE_TAG_EXSCAN, comm,
                                 MPI_STATUS_IGNORE));
    }

    /* Otherwise, get the result from the prior rank, combine it with my
     * data, and send it to the next rank */

    /* Get a temporary buffer to perform the reduction into.  Rationale
     * for malloc'ing this size is provided in coll_basic_reduce.c. */
    ompi_datatype_get_extent(dtype, &lb, &extent);
    ompi_datatype_get_true_extent(dtype, &true_lb, &true_extent);

    free_buffer = (char*)malloc(true_extent + (count - 1) * extent);
    if (NULL == free_buffer) {
        return OMPI_ERR_OUT_OF_RESOURCE;
    }
    reduce_buffer = free_buffer - lb;
    err = ompi_datatype_copy_content_same_ddt(dtype, count, 
                                              reduce_buffer, (char*)sbuf);

    /* Receive the reduced value from the prior rank */
    err = MCA_PML_CALL(recv(rbuf, count, dtype, rank - 1,
                            MCA_COLL_BASE_TAG_EXSCAN, comm, MPI_STATUS_IGNORE));
    if (MPI_SUCCESS != err) {
        goto error;
    }

    /* Now reduce the prior rank's result with my source buffer.  The source
     * buffer had been previously copied into the temporary reduce_buffer. */
    ompi_op_reduce(op, rbuf, reduce_buffer, count, dtype);

    /* Send my result off to the next rank */
    err = MCA_PML_CALL(send(reduce_buffer, count, dtype, rank + 1,
                            MCA_COLL_BASE_TAG_EXSCAN,
                            MCA_PML_BASE_SEND_STANDARD, comm));
    /* Error */
  error:
    free(free_buffer);

    /* All done */
    return err;
}
void MoodBoxServer::getNextChannelMessageUrl(Callback callback, QVariant state, qint32 channelId, qint32 lastMessageId, bool skipMessage)
{
    send(callback, state, new GetNextChannelMessageUrl(channelId, lastMessageId, skipMessage));
}
Beispiel #23
0
int main(int argc, char *argv[])

{

 struct sockaddr_in    pin;

  int   mysock;

  char  buf[8192];

  char  *str="http://140.116.226.211/123.txt 0 0";
  char  *str1="tt 0 0";
  int flag = 0;

  /* 建立server IPv4位址 */

  bzero(&pin, sizeof(pin));

  pin.sin_family = AF_INET;

  pin.sin_addr.s_addr = inet_addr("140.116.226.205");

  pin.sin_port = htons(port);





  /* 建立socket */

while(1){


  mysock = socket(AF_INET, SOCK_STREAM, 0);

  if (mysock == -1) {

        perror("call to socket");

        exit(1);

  }

  /* 連結server */

  if (connect(mysock, (void *)&pin, sizeof(pin)) == -1) {

        perror("call to connect");

        exit(1);

  }

  /* 將str字串傳給 server */

  //printf("Sending message %s to server ...\n", str);

if(flag ==0){

  if (send(mysock, str, strlen(str), 0) == -1) {

        perror("Error in send\n");

        exit(1);

  }
flag = 1;

}

while(1)
{


  /* 接收 server 回傳的訊息 */
  if (recv(mysock, buf, 8192, 0) == -1) {
        perror("Error in receiving\n");
        exit(1);
  }
printf("@%c",buf[0]);
  if(buf[0]=='g'){
    if (send(mysock, str1, strlen(str1), 0) == -1) {
        perror("Error in send\n");
        exit(1);
   buf[0]=='z';
  }

}

  printf("\nResponse from server: \n\n%s\n", buf);
 }
}


  /* 關閉與server的連線 */

  close(mysock);

  return 0;

}
void MoodBoxServer::addUserToChannel(Callback callback, QVariant state, qint32 channelId)
{
    send(callback, state, new AddUserToChannel(channelId));
}
int main()
{
//=====================================================================
// Initialize variables
//=====================================================================
  
  int running,n=0,arg,time=0;
  double dist=0,angle=0;
  count = 1;
  reg_k = 0.35;
  

//=====================================================================
// Establish connection to robot sensors and actuators.
//=====================================================================
  
     if (rhdConnect('w',"localhost",ROBOTPORT)!='w'){
         printf("Can't connect to rhd \n");
	 exit(EXIT_FAILURE); 
      } 
      
      printf("connected to robot \n");
      if ((inputtable=getSymbolTable('r'))== NULL){
         printf("Can't connect to rhd \n");
	 exit(EXIT_FAILURE); 
      }
      if ((outputtable=getSymbolTable('w'))== NULL){
         printf("Can't connect to rhd \n");
	 exit(EXIT_FAILURE); 
      }
      // connect to robot I/O variables
      lenc=getinputref("encl",inputtable);
      renc=getinputref("encr",inputtable);
      linesensor=getinputref("linesensor",inputtable);
      irsensor=getinputref("irsensor",inputtable);
           
      speedl=getoutputref("speedl",outputtable);
      speedr=getoutputref("speedr",outputtable);
      resetmotorr=getoutputref("resetmotorr",outputtable);
      resetmotorl=getoutputref("resetmotorl",outputtable);

      
//=====================================================================
// Camera server code initialization
//=====================================================================

/* Create endpoint */
   lmssrv.port=24919;
   strcpy(lmssrv.host,"127.0.0.1");
   strcpy(lmssrv.name,"laserserver");
   lmssrv.status=1;
   camsrv.port=24920;
   strcpy(camsrv.host,"127.0.0.1");
   camsrv.config=1;
   strcpy(camsrv.name,"cameraserver");
   camsrv.status=1;

   if (camsrv.config) {
      int errno = 0; 
      camsrv.sockfd = socket(AF_INET, SOCK_STREAM, 0);
   if ( camsrv.sockfd < 0 )
   {
    perror(strerror(errno));
    fprintf(stderr," Can not make  socket\n");
    exit(errno);
   }

   serverconnect(&camsrv);

   xmldata=xml_in_init(4096,32);
   printf(" camera server xml initialized \n");

}   


//=====================================================================
// LMS server code initialization
//=====================================================================

/* Create endpoint */
   lmssrv.config=1;
   if (lmssrv.config) {
       char buf[256];
      int errno = 0,len; 
      lmssrv.sockfd = socket(AF_INET, SOCK_STREAM, 0);
   if ( lmssrv.sockfd < 0 )
   {
    perror(strerror(errno));
    fprintf(stderr," Can not make  socket\n");
    exit(errno);
   }

   serverconnect(&lmssrv);
   if (lmssrv.connected){
     xmllaser=xml_in_init(4096,32);
     printf(" laserserver xml initialized \n");
     len=sprintf(buf,"scanpush cmd='zoneobst'\n");
     send(lmssrv.sockfd,buf,len,0);
   }

}   
   
 
  /* Read sensors and zero our position.
   */
  rhdSync();
  
  odo.w=WHEEL_SEPARATION;
  odo.cr=DELTA_M;
  odo.cl=odo.cr;
  odo.left_enc=lenc->data[0];
  odo.right_enc=renc->data[0];
  reset_odo(&odo);
  running=1; 
  mission.state=ms_init;
  mission.oldstate=-1;
  
  reset_sen(&sen);
  
  
//=====================================================================
// Main program loop
//=====================================================================

while (running){ 
    if (lmssrv.config && lmssrv.status && lmssrv.connected){
      while ( (xml_in_fd(xmllaser,lmssrv.sockfd) >0))
	xml_proca(xmllaser);
    }
    if (camsrv.config && camsrv.status && camsrv.connected){
      while ( (xml_in_fd(xmldata,camsrv.sockfd) >0))
        xml_proc(xmldata);
    }
       
  rhdSync();
  update_odo(&odo);
  update_sen(&sen);
  update_motcon(&mot);
  
//=====================================================================
// Mission reading function !!!!!!MAKE!!!!!
//=====================================================================
  if(fwd(3,0.5,time,&mot) == 1)
    running = 0;

//printf("%f %f %f %f %f %d %d %d\n",sen.irarr[0],sen.irarr[1],sen.irarr[2],sen.irarr[3],sen.irarr[4]);
  
  speedl->data[0]=100*mot.motorspeed_l;
  speedl->updated=1;
  speedr->data[0]=100*mot.motorspeed_r;
  speedr->updated=1;
  if (time  % 100 ==0)
    time++;
  
/* stop if keyboard is activated
*
*/
  ioctl(0, FIONREAD, &arg);
  if (arg!=0)  running=0;
    
}/* end of main control loop */
  speedl->data[0]=0;
  speedl->updated=1;
  speedr->data[0]=0;
  speedr->updated=1;
  rhdSync();
  rhdDisconnect();
  exit(0);
}
void MoodBoxServer::deleteUserFromChannel(Callback callback, QVariant state, qint32 channelId)
{
    send(callback, state, new DeleteUserFromChannel(channelId));
}
Beispiel #27
0
void * server_reciever_thread(void* arg)
{
 int len;  // recieved string lenght
 char buffer[200]; // buffer for recieved message

 // prevzeti vstupnich argumentu id clienta
 int new_fd =(int)arg;

 // tahani data z socketu a rozesilani vsem
 while ((len = recv(new_fd, buffer, sizeof(buffer)-1, 0)) > 0) 
 {
  buffer[len-2] = 0; /* mark end of string */

  long noveOtacky;
  char* p;
  noveOtacky = strtol(buffer, &p, 0);

  // prevod str na cislo
  if ((p == buffer) || *p)
  {
    //vypise na serveru ze to klient zadal blbe
    printf("Klient zadal nesmyslny pozadavek:%s\n",buffer);
    fflush(stdout);
    // odesli zpravu klientovi ze to zadal blbe
    const char msg[] = "Zadal jste nesmysl \n";
    send(new_fd, msg, strlen(msg), 0);
  }
  
  // kdyz to tedy cislo je
  else
  {
   // kontrola zda je to v mezich od -10000 do +10000
   if(noveOtacky<-10000  || noveOtacky>10000)
   {
    // oznameni na severu ze klient zadal cislo mimo rozsah
    printf("Klient zadal cislo mimo rozsah otacek: %d \n",(int)noveOtacky);
    fflush(stdout);
    // oznameni klintovi ze zadal moc velke cislo 
    const char msg[] = "Prilis vysoke otacky \n";
    send(new_fd, msg, strlen(msg), 0);
   }

   // kdyz je vse v poradku, tak se prepisy otacky
   else
   {
    pthread_mutex_lock(&mutex_demandRotates); 
      demandRotates = noveOtacky;
    pthread_mutex_unlock(&mutex_demandRotates); 
    printf("Klient zadal pozadavek na otacky: %d ot/min \n",(int)noveOtacky);
    fflush(stdout);
    // oznameni klientovi ze vse probehlo dobre a otacky se nastavily
    char msg[400]; 
    sprintf(msg,"Pozadovane otacky zmeneny na %d ot/min\n",(int)noveOtacky);
    send(new_fd, msg, strlen(msg), 0);
   }
  }

 }// konec cteci smycky, bude z ni vyskoceno kdyz neprijde zadny znak
 // coz je kdyz se klient odpoji

// oznameni se se muze ukoncit toto vlakno
pthread_mutex_lock(&mutex_isClientConnected); 
     printf("Klient se odpojil \n");
     fflush(stdout);
     isClientConnected = FALSE;
pthread_mutex_unlock(&mutex_isClientConnected); 

return NULL;
}
void MoodBoxServer::obsceneChannelMessage(Callback callback, QVariant state, qint32 channelId, qint32 messageId)
{
    send(callback, state, new ObsceneChannelMessage(channelId, messageId));
}
Beispiel #29
0
int http_async_req_status(void *ctx)
{
	struct http_ctx *cx = (http_ctx *)ctx;
	char *dns,*srv,buf[CHUNK];
	int tmp, i;
	time_t now = time(NULL);
#ifdef WIN
	unsigned long tmp2;
#endif

	switch (cx->state)
	{
	case HTS_STRT:
		dns = getserv(cx->host);
		srv = getport(cx->host);
		if (resolve(dns, srv, &cx->addr))
		{
			free(dns);
			free(srv);
			cx->state = HTS_DONE;
			cx->ret = 602;
			return 1;
		}
		free(dns);
		free(srv);
		cx->state = HTS_RSLV;
		return 0;
	case HTS_RSLV:
		cx->state = HTS_CONN;
		cx->last = now;
		return 0;
	case HTS_CONN:
		if (cx->fd == PERROR)
		{
			cx->fd = socket(AF_INET, SOCK_STREAM, 0);
			if (cx->fd == PERROR)
				goto fail;
			cx->fdhost = mystrdup(cx->host);
#ifdef WIN
			tmp2 = 1;
			if (ioctlsocket(cx->fd, FIONBIO, &tmp2) == SOCKET_ERROR)
				goto fail;
#else
			tmp = fcntl(cx->fd, F_GETFL);
			if (tmp < 0)
				goto fail;
			if (fcntl(cx->fd, F_SETFL, tmp|O_NONBLOCK) < 0)
				goto fail;
#endif
		}
		if (!connect(cx->fd, (struct sockaddr *)&cx->addr, sizeof(cx->addr)))
			cx->state = HTS_IDLE;
#ifdef WIN
		else if (PERRNO==WSAEISCONN)
			cx->state = HTS_IDLE;
#endif
#if defined(MACOSX) || defined(BSD)
		else if (PERRNO==EISCONN)
			cx->state = HTS_IDLE;
#endif
		else if (PERRNO!=PEINPROGRESS && PERRNO!=PEALREADY
#ifdef WIN
		         && PERRNO!=PEAGAIN && PERRNO!=WSAEINVAL
#endif
		        )
			goto fail;
		if (now-cx->last>http_timeout)
			goto timeout;
		return 0;
	case HTS_IDLE:
		if (cx->txdl)
		{
			// generate POST
			cx->tbuf = (char *)malloc(strlen(cx->host) + strlen(cx->path) + 132 + strlen(userAgent) + cx->txdl + cx->thlen);
			cx->tptr = 0;
			cx->tlen = 0;
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "POST %s HTTP/1.1\r\n", cx->path);
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "Host: %s\r\n", cx->host);
			if (!cx->keep)
				cx->tlen += sprintf(cx->tbuf+cx->tlen, "Connection: close\r\n");
			if (cx->thdr)
			{
				memcpy(cx->tbuf+cx->tlen, cx->thdr, cx->thlen);
				cx->tlen += cx->thlen;
				free(cx->thdr);
				cx->thdr = NULL;
				cx->thlen = 0;
			}
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "Content-Length: %d\r\n", cx->txdl);
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "User-Agent: %s\r\n", userAgent);
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "\r\n");
			memcpy(cx->tbuf+cx->tlen, cx->txd, cx->txdl);
			cx->tlen += cx->txdl;
			free(cx->txd);
			cx->txd = NULL;
			cx->txdl = 0;
		}
		else
		{
			// generate GET
			cx->tbuf = (char *)malloc(strlen(cx->host) + strlen(cx->path) + 98 + strlen(userAgent) + cx->thlen);
			cx->tptr = 0;
			cx->tlen = 0;
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "GET %s HTTP/1.1\r\n", cx->path);
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "Host: %s\r\n", cx->host);
			if (cx->thdr)
			{
				memcpy(cx->tbuf+cx->tlen, cx->thdr, cx->thlen);
				cx->tlen += cx->thlen;
				free(cx->thdr);
				cx->thdr = NULL;
				cx->thlen = 0;
			}
			if (!cx->keep)
				cx->tlen += sprintf(cx->tbuf+cx->tlen, "Connection: close\r\n");
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "User-Agent: %s\r\n", userAgent);
			cx->tlen += sprintf(cx->tbuf+cx->tlen, "\r\n");
		}
		cx->state = HTS_XMIT;
		cx->last = now;
		return 0;
	case HTS_XMIT:
		tmp = send(cx->fd, cx->tbuf+cx->tptr, cx->tlen-cx->tptr, 0);
		if (tmp==PERROR && PERRNO!=PEAGAIN && PERRNO!=PEINTR)
			goto fail;
		if (tmp!=PERROR && tmp)
		{
			cx->tptr += tmp;
			if (cx->tptr == cx->tlen)
			{
				cx->tptr = 0;
				cx->tlen = 0;
				if (cx->tbuf)
				{
					free(cx->tbuf);
					cx->tbuf = NULL;
				}
				cx->state = HTS_RECV;
			}
			cx->last = now;
		}
		if (now-cx->last>http_timeout)
			goto timeout;
		return 0;
	case HTS_RECV:
		tmp = recv(cx->fd, buf, CHUNK, 0);
		if (tmp==PERROR && PERRNO!=PEAGAIN && PERRNO!=PEINTR)
			goto fail;
		if (tmp!=PERROR && tmp)
		{
			for (i=0; i<tmp; i++)
			{
				process_byte(cx, buf[i]);
				if (cx->state == HTS_DONE)
					return 1;
			}
			cx->last = now;
		}
		if (now-cx->last>http_timeout)
			goto timeout;
		return 0;
	case HTS_DONE:
		return 1;
	}
	return 0;

fail:
	cx->ret = 600;
	cx->state = HTS_DONE;
	return 1;

timeout:
	cx->ret = 605;
	cx->state = HTS_DONE;
	return 1;
}
void MoodBoxServer::sendPrivateMessage(Callback callback, QVariant state, qint32 recipientId, QByteArray message, QString metadata)
{
    send(callback, state, new SendPrivateMessage(recipientId, message, metadata));
}