Beispiel #1
0
int ScanThread::recvm(struct message* m, SOCKET s, unsigned long int *ip, unsigned short int *port) 
{
  struct sockaddr_in from;
  int bsize;
  static unsigned char buf[MAX_PACKET_LEN];
#ifdef __WIN32__
  int ssize  = sizeof(struct sockaddr_in);
#else
  socklen_t ssize  = sizeof(struct sockaddr_in);
#endif
 

  if((bsize = recvfrom(s, (char*)buf, MAX_PACKET_LEN, 0, (struct sockaddr*)&from, &ssize)) > 0)
    {
      memset(m, '\0', sizeof(struct message));
      message_parse(m,buf);
      *ip = (unsigned long int)from.sin_addr.s_addr;
      *port = from.sin_port;
      return bsize;
    }

#ifdef __WIN32__
  if(bsize < 0 && WSAGetLastError() != WSAEWOULDBLOCK) 
#else
    if(bsize < 0 && errno != EAGAIN)
#endif
      {
	p->err.Printf(_("Can't read from socket %d: %s\n"),
		      errno,strerror(errno));
	return bsize;
      }

  return 0;
}
Beispiel #2
0
int main(int argc, char *argv[])
{
    mdnsd d;
    struct message m;
    unsigned long int ip;
    unsigned short int port;
    struct timeval *tv;
    int bsize, ssize = sizeof(struct sockaddr_in);
    unsigned char buf[MAX_PACKET_LEN];
    struct sockaddr_in from, to;
    fd_set fds;
    int s;

    if(argc != 3) { printf("usage: mquery 12 _http._tcp.local.\n"); return; }

    d = mdnsd_new(1,1000);
    if((s = msock()) == 0) { printf("can't create socket: %s\n",strerror(errno)); return 1; }

    mdnsd_query(d,argv[2],atoi(argv[1]),ans,0);

    while(1)
    {
        tv = mdnsd_sleep(d);
        FD_ZERO(&fds);
        FD_SET(s,&fds);
        select(s+1,&fds,0,0,tv);

        if(FD_ISSET(s,&fds))
        {
            while((bsize = recvfrom(s,buf,MAX_PACKET_LEN,0,(struct sockaddr*)&from,&ssize)) > 0)
            {
                bzero(&m,sizeof(struct message));
                message_parse(&m,buf);
                mdnsd_in(d,&m,(unsigned long int)from.sin_addr.s_addr,from.sin_port);
            }
            if(bsize < 0 && errno != EAGAIN) { printf("can't read from socket %d: %s\n",errno,strerror(errno)); return 1; }
        }
        while(mdnsd_out(d,&m,&ip,&port))
        {
            bzero(&to, sizeof(to));
            to.sin_family = AF_INET;
            to.sin_port = port;
            to.sin_addr.s_addr = ip;
            if(sendto(s,message_packet(&m),message_packet_len(&m),0,(struct sockaddr *)&to,sizeof(struct sockaddr_in)) != message_packet_len(&m))  { printf("can't write to socket: %s\n",strerror(errno)); return 1; }
        }
    }

    mdnsd_shutdown(d);
    mdnsd_free(d);
    return 0;
}
static void server_loop(TestInstanceServer *inc)
{
    struct message m;
    struct timeval *tv;
    MDDSocketAddr_t to_addr, from_addr;
    MDDIface_t to_iface, from_iface;
    MDDFDSet_t fds;
    mdnsd mdnsd;
    MDDSocket_t socket_ipv4;
    int rsize = 0;
    unsigned char buf[MAX_PACKET_LEN] = {0};

    mdnsd = inc->mdnsd;
    socket_ipv4 = inc->socket_ipv4;

    while (1) {
        tv = mdnsd_sleep(mdnsd);
        MDDFDUtil_FDZero(&fds);
        MDDFDUtil_FDSet(socket_ipv4, &fds);

        MDDFDUtil_FDSelect(socket_ipv4 + 1, &fds, 0, 0, tv);

        // handle incoming packet
        if (MDDFDUtil_FDIsset(socket_ipv4, &fds)) {
            from_addr.family = MDDNet_INET;
            while ((rsize = MDDSocket_Recvfrom(socket_ipv4, buf, MAX_PACKET_LEN, &from_addr, &from_iface)) > 0) {
                memset(&m, 0, sizeof(struct message));
                message_parse(&m, buf, rsize);
                mdnsd_in(inc->mdnsd, &m, &from_addr, &from_iface);
            }
        }

        // handle outgoing packet
        memset(&m, 0, sizeof(struct message));
        while (mdnsd_out(mdnsd, &m, &to_addr, &to_iface)) {
            if (to_addr.family == MDDNet_INET) {
                if (MDDSocket_Sendto(socket_ipv4, message_packet(&m), message_packet_len(&m), &to_addr, &to_iface) != message_packet_len(&m)) {
                    printf("can't write to ipv4 socket, ifindex: %u\n", to_iface.ifindex);
                }
            } else {
                printf("error when send packet, unsupport address family: %d\n", to_addr.family);
            }
        }
        if (inc->sn > inc->max_sn) {
            break;
        }
    }
}
Beispiel #4
0
int main(int argc, char *argv[])
{
    mdnsd d;
    mdnsdr r;
    struct message m;
    unsigned long int ip;
    unsigned short int port;
    struct timeval *tv;
    int bsize, ssize = sizeof(struct sockaddr_in);
    unsigned char buf[MAX_PACKET_LEN];
    struct sockaddr_in from, to;
    fd_set fds;
    int s;
    unsigned char *packet, hlocal[256], nlocal[256];
    int len = 0;
    xht h;

    if(argc < 4) { printf("usage: mhttp 'unique name' 12.34.56.78 80 '/optionalpath'\n"); return; }

    ip = inet_addr(argv[2]);
    port = atoi(argv[3]);
    printf("Announcing .local site named '%s' to %s:%d and extra path '%s'\n",argv[1],inet_ntoa(ip),port,argv[4]);

    signal(SIGINT,done);
    signal(SIGHUP,done);
    signal(SIGQUIT,done);
    signal(SIGTERM,done);
    pipe(_zzz);
    _d = d = mdnsd_new(1,1000);
    if((s = msock()) == 0) { printf("can't create socket: %s\n",strerror(errno)); return 1; }

    sprintf(hlocal,"%s._http._tcp.local.",argv[1]);
    sprintf(nlocal,"http-%s.local.",argv[1]);
    r = mdnsd_shared(d,"_http._tcp.local.",QTYPE_PTR,120);
    mdnsd_set_host(d,r,hlocal);
    r = mdnsd_unique(d,hlocal,QTYPE_SRV,600,con,0);
    mdnsd_set_srv(d,r,0,0,port,nlocal);
    r = mdnsd_unique(d,nlocal,QTYPE_A,600,con,0);
    mdnsd_set_raw(d,r,(unsigned char *)&ip,4);
    r = mdnsd_unique(d,hlocal,16,600,con,0);
    h = xht_new(11);
    if(argc == 5 && argv[4] && strlen(argv[4]) > 0) xht_set(h,"path",argv[4]);
    packet = sd2txt(h, &len);
    xht_free(h);
    mdnsd_set_raw(d,r,packet,len);
    free(packet);

    while(1)
    {
        tv = mdnsd_sleep(d);
        FD_ZERO(&fds);
        FD_SET(_zzz[0],&fds);
        FD_SET(s,&fds);
        select(s+1,&fds,0,0,tv);

        // only used when we wake-up from a signal, shutting down
        if(FD_ISSET(_zzz[0],&fds)) read(_zzz[0],buf,MAX_PACKET_LEN);

        if(FD_ISSET(s,&fds))
        {
            while((bsize = recvfrom(s,buf,MAX_PACKET_LEN,0,(struct sockaddr*)&from,&ssize)) > 0)
            {
                bzero(&m,sizeof(struct message));
                message_parse(&m,buf);
                mdnsd_in(d,&m,(unsigned long int)from.sin_addr.s_addr,from.sin_port);
            }
            if(bsize < 0 && errno != EAGAIN) { printf("can't read from socket %d: %s\n",errno,strerror(errno)); return 1; }
        }
        while(mdnsd_out(d,&m,&ip,&port))
        {
            bzero(&to, sizeof(to));
            to.sin_family = AF_INET;
            to.sin_port = port;
            to.sin_addr.s_addr = ip;
            if(sendto(s,message_packet(&m),message_packet_len(&m),0,(struct sockaddr *)&to,sizeof(struct sockaddr_in)) != message_packet_len(&m))  { printf("can't write to socket: %s\n",strerror(errno)); return 1; }
        }
        if(_shutdown) break;
    }

    mdnsd_shutdown(d);
    mdnsd_free(d);
    return 0;
}
Beispiel #5
0
void
str_cli(int sockfd)
{
  char	*sendline, recvline[MESSAGE_MAXLEN], opt[100];
  int ch;
  char option[100];
  message_t newMesg;
  fd_set readset;
  char invite[MAXLENGTH];
  
    while(1)
      {
  	ch = menu();
	switch(ch)
	  {
	  case 1:
	    printf("\n\n----------------------------------------------------------------------------------------\nSIGN IN\n");
	    sendline = message_toString(getIdAndPassword(SIGNIN));
		
		if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("Server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    newMesg = message_parse(recvline);
	    newMesg->arg[1] = '\0';
	    newMesg->arg1[1] = '\0';

	    switch(newMesg->cmd) {
	    	case SIGNIN:
	    	printf("\nWelcome to console chess game\n");
	    	menuPlay();

	    	while(1) {
	    		FD_ZERO(&readset);
				FD_SET(sockfd, &readset);
				FD_SET(fileno(stdin), &readset);
				select(max(sockfd, fileno(stdin)) + 1, &readset, NULL, NULL, NULL);
				if(FD_ISSET(sockfd, &readset)) {
					if(read(sockfd, recvline, MESSAGE_MAXLEN) == 0) {
						printf("Server terminated prematurely\n");
						exit(1);
					}
					//TODO: receive invitation
					newMesg = message_parse(recvline);

					switch(newMesg->cmd) {
					case INVITE_ACCEPT:
					printf("Client %s invited you to his/her game (y/n) ?\n", newMesg->arg1);
					scanf("%s", opt);
					if(strcmp(opt, "y") == 0 || strcmp(opt, "Y") == 0) {
						if (send(sockfd, recvline, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
				            printf("send() sent a different number of bytes than expected\n");
				        }
					}
					else {
						if (send(sockfd, message_toString( message_construct(INVITE_DECLINE, newMesg->arg1, "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
				            printf("send() sent a different number of bytes than expected\n");
				        }
					}
					break;
					case PICK_SIDE:
					if(strcmp(newMesg->arg, "0") == 0) {
					 	mainConsoleChess(0, sockfd);
					 	menuPlay();
					}
					else if (strcmp(newMesg->arg, "1") == 0) {
						mainConsoleChess(1, sockfd);
						menuPlay();
					}
					case GET_PLAYERLIST:
					parse(newMesg->arg);
					menuPlay();
					break;

					default:
					printf("Cannot get the message\n");
					break;
					}


				} else if(FD_ISSET(fileno(stdin), &readset)) {
					fgets(option, 100, stdin);
					option[strlen(option) -1] = '\0';
					if(strcmp(option, "1") == 0) {
						//TODO: inviting someone
						printf("Type the one'id who you want to invite\n");
						scanf("%s", invite);
						
						if (send(sockfd, message_toString(message_construct(INVITE_SEND, invite, "0", "0", "0")), MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
		     				 printf("send() sent a different number of bytes than expected\n");
		    			}
		    			printf("Waiting for responding from server...\n");
					    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
					      printf("Server terminated prematurely\n");
					      exit(1);
					    }
					    recvline[strlen(recvline)] = '\0';
					    newMesg = message_parse(recvline);
					    newMesg->arg[1] = '\0';
					    if(newMesg->cmd == PICK_SIDE) {
							if(strcmp(newMesg->arg, "0") == 0) {
							 	mainConsoleChess(0, sockfd);
							 	menuPlay();
							}
							else if (strcmp(newMesg->arg, "1") == 0) {
								mainConsoleChess(1, sockfd);
								menuPlay();
							}							    	
					    }
					    else {
					    	printf("He/she declined your request\n");
					    	menuPlay();
					    }

					} else if(strcmp(option, "2") == 0) {
						//TODO: get the current players list from server
						if (send(sockfd, message_toString(message_construct(GET_PLAYERLIST, "0", "0", "0", "0")), MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	     					 printf("send() sent a different number of bytes than expected\n");
	    				}
	    				printf("Waiting for responding from server...\n");
					} else if(strcmp(option, "3") == 0) {
						printf("Thanks for enjoying\n");
						break;
					} else {
						printf("Not the right option, baby\n");
						menuPlay();
						continue;
					}
				}
			}
	    	break;


	    	default:
	    	printf("MESSAGE COMMAND: %d\n", newMesg->cmd);
	    	printf("Fail to sign in\n");
	    	break;
	    }

	    continue;

	  case 2:
	    printf("\n\n----------------------------------------------------------------------------------------\nSIGN UP\n");
	    sendline = message_toString(getIdAndPassword(SIGNUP));

	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN ) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';

	    newMesg = message_parse(recvline);
	    switch(newMesg->cmd) {
	    	case SIGNUP:
	    	printf("\nSuccessfull sign up\n");
	    	break;
	    	default:
	    	printf("Fail to sign up. Maybe this account doesn't exist\n");
	    	break;
	    }
	    continue;

	  case 3:
	    printf("----------------------------------------------------------------------------------------\nExit\n");
	    sendline = message_toString(message_construct(SIGNOUT, "0", "0", "0", "0"));
	    
	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("Server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    printf("\nI'm done!\n");
	    exit(0);
	    break;

	  default:
	    printf("Wrong option! Please choose again\n");
	    continue;
	  }
	break;
      }
    printf("\n");
  
	
}
Beispiel #6
0
int main(){

  int serv_sockfd, client_sockfd;
  int server_len, client_len, bytes_received;

  struct sockaddr_in server_addr;
  struct sockaddr_in client_addr;

  char recv_data[1024], send_data[1024], recvdata[1024];
  int result;
  int fd;
  int nread;
  struct timeval tv;
  fd_set fdset, testfds;

  char id[MAXLENGTH], password[MAXLENGTH];

  serv_sockfd = socket(AF_INET, SOCK_STREAM, 0);
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(1234);
  server_len = sizeof(server_addr);
  
  //Create a TCP/IP socket to use
  if ((serv_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Socket() error");
    exit(1);
  }

  if (bind(serv_sockfd, (struct sockaddr *)&server_addr, server_len)== -1) {
    perror("bind() error");
    exit(1);
  }

  if (listen(serv_sockfd, 5) == -1) {
    perror("Listen() error");
    exit(1);
  }

  FD_ZERO(&fdset);    /*clear all bits in fdset*/
  FD_SET(serv_sockfd, &fdset);  /*turn on the bit for fd in fdset*/

  while(1) {    
    /* wait until either socket has data ready to be recv()d (timeout 5.5 secs)*/
    tv.tv_sec = 5;
    tv.tv_usec = 500000;
    testfds = fdset;
    printf("Server waiting\n");
    
    result = select(FD_SETSIZE, &testfds, (fd_set *)NULL,(fd_set *)NULL, &tv);
    
    if(result == -1) {
      perror("Select() error");   // error occurred in select() 
      exit(1);
    }
    else if(result == 0){
      printf("Timeout occurred! No data after 5.5 seconds.\n");    
       
    }
    else{
      //Client connected
      for(fd = 0; fd < FD_SETSIZE; fd++){
	if(FD_ISSET(fd,&testfds)) {
	  if(fd == serv_sockfd){
	    printf("Request on port %d\n", fd);

       client_len = sizeof(client_addr);
	     client_sockfd = accept(serv_sockfd,(struct sockaddr *)&client_addr, &client_len);
	     FD_SET(client_sockfd, &fdset);
	     printf("Client %d connected !\n", client_sockfd);
	  }
	  else {
	    ioctl(fd, FIONREAD, &nread);
	    if(nread != 0) {
	      printf("\nHandling on socket %d\n",fd);
	      //TODO: Handle socket here

        bytes_received = recv(fd,recv_data,1024,0);
	      recv_data[bytes_received] = '\0';
        message_t newMesg = message_parse(recv_data);
        
        switch(newMesg->cmd) {
          case SIGNIN:            
            strcpy(id, newMesg->arg);
            printf("%s\n", id);
            strcpy(password, newMesg->arg1);
            printf("%s\n", password);
            //TODO: check sign in here

            if(1) {
              if (send(fd, recv_data, strlen(recv_data), 0) != strlen(recv_data)) {
                printf("send() sent a different number of bytes than expected\n");
              }         
              //TODO: play module here
            }
            else {
              if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), 1024, 0) != 1024) {
                printf("send() sent a different number of bytes than expected\n");
              }
            }
            
          break;
          case SIGNUP:
            strcpy(id, newMesg->arg);
            printf("%s\n", id);
            strcpy(password, newMesg->arg1);
            printf("%s\n", password);
            //TODO Check account here

            if(1) {
              if (send(fd, recv_data, strlen(recv_data), 0) != strlen(recv_data)) {
                printf("send() sent a different number of bytes than expected\n");
              }         
            }
            else {
              if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), 1024, 0) != 1024) {
                printf("send() sent a different number of bytes than expected\n");
              }
            }

          break;
          case SIGNOUT:
            // TODO: decrease player counter
            if (send(fd, recv_data, strlen(recv_data), 0) != strlen(recv_data)) {
              printf("send() sent a different number of bytes than expected\n");
            }
          break;
          default:
          printf("Error occurred\n");

          if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), 1024, 0) != 1024) {
            printf("send() sent a different number of bytes than expected\n");
          }
          break;
        }

	    } 
	    else {
	      close(fd);
	      FD_CLR(fd, &fdset);  /*turn off the bit for fd in fdset*/
	      printf("Not connect client on fd %d\n", fd);
	    }
	  }
	}
      }
    }
  }
  close(serv_sockfd);
}
Beispiel #7
0
int main ()
{
    gameserver_core_init ();
    gameserver_core_loadUsers ();

    /**
     * Server connection handling
     */
    char temp[1024];
    int enemySide, otherSide;
    int randomNum, userCounter = 0;
    int serv_sockfd, client_sockfd;
    int bytes_received;
    socklen_t server_len, client_len;

    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;

    char recv_data[1024];
    int result;
    int fd;
    int nread;
    struct timeval tv;
    fd_set fdset, testfds;

    serv_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(1234);
    server_len = sizeof(server_addr);

    //Create a TCP/IP socket to use
    if ((serv_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Socket() error");
        exit(1);
    }

    if (bind(serv_sockfd, (struct sockaddr *)&server_addr, server_len)== -1) {
        perror("bind() error");
        exit(1);
    }

    if (listen(serv_sockfd, 5) == -1) {
        perror("Listen() error");
        exit(1);
    }

    FD_ZERO(&fdset);    /*clear all bits in fdset*/
    FD_SET(serv_sockfd, &fdset);  /*turn on the bit for fd in fdset*/

    while(1) {
        /* wait until either socket has data ready to be recv()d (timeout 5.5 secs)*/
        tv.tv_sec = 5;
        tv.tv_usec = 500000;
        testfds = fdset;

        result = select(FD_SETSIZE, &testfds, (fd_set *)NULL,(fd_set *)NULL, &tv);

        if(result == -1) {
            perror("Select() error");   // error occurred in select()
            exit(1);
        }
        else if(result == 0){
//            printf("Timeout occurred! No data after 5.5 seconds.\n");
        }
        else{
            //Client connected
            for(fd = 0; fd < FD_SETSIZE; fd++){
                if(FD_ISSET(fd,&testfds)) {
                    if(fd == serv_sockfd){
                        printf("Request on port %d\n", fd);

                        client_len = sizeof(client_addr);
                        client_sockfd = accept(serv_sockfd,(struct sockaddr *)&client_addr, &client_len);
                        FD_SET(client_sockfd, &fdset);
                        printf("Client %d connected !\n", client_sockfd);
                    }
                    else {
                        ioctl(fd, FIONREAD, &nread);
                        if(nread != 0) {
                            printf("\nHandling on socket %d\n",fd);
                            // Handle socket here
                            bytes_received = recv(fd,recv_data,1024,0);
                            recv_data[bytes_received] = '\0';
                            message_t newMesg = message_parse(recv_data);


                            /**
                             * Game server business logic
                             */
                            int response = 0;
                            char logStr[100];
                            switch(newMesg->cmd) {
                                case SIGNIN:
                                    {
                                    	sprintf (logStr, "User signing in at port %d", fd);
                                    	logging (logStr);
                                        response = gameserver_core_signin (newMesg->arg, newMesg->arg1, fd);
                                        if (response >= 0) {
                                            if (send(fd, recv_data, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
                                                printf("send() sent a different number of bytes than expected\n");
                                            }
                                            userCounter++;
                                            gameserver_core_signin(newMesg->arg, newMesg->arg1, fd);
                                           	sprintf (logStr, "User %s signed in at port %d", newMesg->arg, fd);
                                           	logging (logStr);
                                        } else {
                                            printf("SEND THIS COMMAND: %d\n", FAILURE);
                                            if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                                printf("send() sent a different number of bytes than expected\n");
                                            }
                                        }
                                    }
                                    break;

                                case SIGNUP:
                                    response = gameserver_core_signup (newMesg->arg, newMesg->arg1);
                                    if(response > 0) {
                                        if (send(fd, recv_data, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
                                            printf("send() sent a different number of bytes than expected\n");
                                        }
                                        gameserver_core_signup(newMesg->arg, newMesg->arg1);
                                        sprintf (logStr, "User %s signup in at port %d", newMesg->arg, fd);
                                    	logging (logStr);
                                    }
                                    else {
                                        if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                            printf("send() sent a different number of bytes than expected\n");
                                        }
                                    }
                                    break;

                                case SIGNOUT:
                                    // TODO: decrease player counter
                                    if (send(fd, recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                    	sprintf (logStr, "User %s signed out at port %d", newMesg->arg, fd);
                                    	logging (logStr);
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    userCounter--;

                                    break;
                                case MOVE:
                                    //Check the port here
                                	enemySide = gameserver_core_getOtherUserSockfd(fd);
                                    if (send(enemySide, recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                    	sprintf (logStr, "User moved %s in at port %d", newMesg->arg, fd);
                                    	logging (logStr);
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    break;
                                case INVITE_SEND:
                                    //send it to other socket
                                    newMesg->arg[1] = '\0';
                                    enemySide = atoi(newMesg->arg);
                                    sprintf(temp, "%d", fd);
                                    if (send(enemySide, message_toString( message_construct(INVITE_ACCEPT, newMesg->arg, temp, "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                    	sprintf (logStr, "User at port %d sent invite to user at socket %s", fd, newMesg->arg);
                                    	logging (logStr);
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    break;

                                case INVITE_ACCEPT:
                                    newMesg->arg[1] = '\0';
                                    newMesg->arg1[1] = '\0';
                                    enemySide = atoi(newMesg->arg);
                                    otherSide = atoi(newMesg->arg1);
                                    srand(time(NULL));
                                    randomNum = rand() % 2;
                                    sprintf(temp, "%d", randomNum);
                                    if (send(enemySide, message_toString( message_construct(PICK_SIDE, temp, "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    sprintf(temp, "%d", randomNum ^ 1);
                                    if (send(otherSide, message_toString( message_construct(PICK_SIDE, temp, "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    //TODO: change status of user here
									sprintf (logStr, "Challege accepted :-< Battle has begun %d vs. %d", enemySide, otherSide);
                                    logging (logStr);
                                    gameserver_core_initNewRoom(enemySide, otherSide);
                                    break;
                                case INVITE_DECLINE:
                                	newMesg->arg[1] = '\0';
                                    newMesg->arg1[1] = '\0';
                                    if (send(atoi(newMesg->arg), recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                    	sprintf (logStr, "User %d declined", fd);
                                    	logging (logStr);
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                break;
                                case RESULT:
                                	if (send(fd, message_toString( message_construct(SIGNOUT, "0", "0", "0", "0")), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    enemySide = gameserver_core_getOtherUserSockfd(fd);
                                    if (send(enemySide, message_toString( message_construct(SIGNOUT, "0", "0", "0", "0")), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    sprintf (logStr, "The war is over :-< ");
                                    logging (logStr);
                                break;
                                case GET_PLAYERLIST:
                                    if (send(fd, message_toString( message_construct(GET_PLAYERLIST, gameserver_core_getPlayerlist(), "0", "0", "0")), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    sprintf (logStr, "User %d requested player list", fd);
                                    logging (logStr);
                                break;
                                default:
                                    printf("Error occurred\n");

                                    if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                                        printf("send() sent a different number of bytes than expected\n");
                                    }
                                    break;
                            }

                        }
                        else {
                            close(fd);
                            FD_CLR(fd, &fdset);  /*turn off the bit for fd in fdset*/
                            printf("Not connect client on fd %d\n", fd);
                            userCounter--;
                            //TODO change user status here
							enemySide = gameserver_core_getOtherUserSockfd(fd);
                            // if (send(enemySide, message_toString( message_construct(RESULT, "1/2", "1/2", "0", "0") ) , MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                            // 	printf("send() sent a different number of bytes than expected\n");
                            // }
                        }
                    }
                }
            }
        }
    }
    gameserver_core_endSession();
    close(serv_sockfd);
}
Beispiel #8
0
void process_messages()
{
#ifdef UART0_DISCONNECT_ON_DTR
	if ((PORT_UART0_DTR & (1 << PIN_UART0_DTR)))
	{
		if (state == StateConnected)
		{
			send_error(ErrorDisconnect, 0);
		}
		uart0_flush();
		return;
	}
#endif
	MessageParseResult res;
	while ((res = message_parse()) == ParseOk)
	{
		switch (message.identifier)
		{
			case IdAckMessage:
				handle_ack();
				break;
			case IdInitMessage:
				handle_init();
				break;
			case IdFootSwitchMessage:
				handle_footswitch();
				break;
			case IdInterlockResetMessage:
				handle_int_reset();
				break;
			case IdServoCtrlMessage:
				handle_servo_ctrl();
				break;
			case IdDockingLimitMessage:
				handle_docking_limit();
				break;
			case IdErrorMessage:
				handle_error();
				break;
			case IdDockingTareMessage:
				handle_docking_tare();
				break;
			case IdSettingsMessage:
				handle_settings();
				break;
			default:
				send_error(ErrorUnhandled, message.sequence);
				return;
		}
	}

	switch (res)
	{
		case ParseNotEnoughData: // buffer empty, done
			break;
//		case ParseInvalidIdentifier: // fall
//		case ParseInvalidSizeError: // fall
//		case ParseChecksumError: // fall
		default:
			send_error(ErrorParser, 0);
			break;
	}
}
Beispiel #9
0
int main(){

  //FOR DEBUGGING
  char id1[100] = "Hung", password1[100] = "123456", id2[100] = "Huy", password2[100] = "123456", temp[100];
  int socket1, socket2;
  int serv_sockfd, client_sockfd;
  int server_len, client_len, bytes_received;

  struct sockaddr_in server_addr;
  struct sockaddr_in client_addr;

  char recv_data[1024], send_data[1024], recvdata[1024];
  int result;
  int fd;
  int nread;
  struct timeval tv;
  fd_set fdset, testfds;

  char id[MAXLENGTH], password[MAXLENGTH];

  serv_sockfd = socket(AF_INET, SOCK_STREAM, 0);
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(1234);
  server_len = sizeof(server_addr);
  
  //Create a TCP/IP socket to use
  if ((serv_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Socket() error");
    exit(1);
  }

  if (bind(serv_sockfd, (struct sockaddr *)&server_addr, server_len)== -1) {
    perror("bind() error");
    exit(1);
  }

  if (listen(serv_sockfd, 5) == -1) {
    perror("Listen() error");
    exit(1);
  }

  FD_ZERO(&fdset);    /*clear all bits in fdset*/
  FD_SET(serv_sockfd, &fdset);  /*turn on the bit for fd in fdset*/

  while(1) {    
    /* wait until either socket has data ready to be recv()d (timeout 5.5 secs)*/
    tv.tv_sec = 5;
    tv.tv_usec = 500000;
    testfds = fdset;
    printf("Server waiting\n");
    
    result = select(FD_SETSIZE, &testfds, (fd_set *)NULL,(fd_set *)NULL, &tv);
    
    if(result == -1) {
      perror("Select() error");   // error occurred in select() 
      exit(1);
    }
    else if(result == 0){
      printf("Timeout occurred! No data after 5.5 seconds.\n");    
       
    }
    else{
      //Client connected
      for(fd = 0; fd < FD_SETSIZE; fd++){
	if(FD_ISSET(fd,&testfds)) {
	  if(fd == serv_sockfd){
	    printf("Request on port %d\n", fd);

       client_len = sizeof(client_addr);
	     client_sockfd = accept(serv_sockfd,(struct sockaddr *)&client_addr, &client_len);
	     FD_SET(client_sockfd, &fdset);
	     printf("Client %d connected !\n", client_sockfd);
	  }
	  else {
	    ioctl(fd, FIONREAD, &nread);
	    if(nread != 0) {
	      printf("\nHandling on socket %d\n",fd);
	      //TODO: Handle socket here

        bytes_received = recv(fd,recv_data,1024,0);
	      recv_data[bytes_received] = '\0';
        puts(recv_data);
        message_t newMesg = message_parse(recv_data);
        
        switch(newMesg->cmd) {
          case SIGNIN:            
            strcpy(id, newMesg->arg);
            printf("The ID: %s\nID 1: %s\nID 2: %s\n", id, id1, id2); //DEBUGGING
            strcpy(password, newMesg->arg1);
            printf("The password: %s\nPassword 1: %s\nPassword 2: %s", password, password1, password2); //DEBUGGING
            //TODO: check sign in here

            //FOR DEBUGGING
            printf("%s\n", message_toString(newMesg));
            if((strcmp(id, id1) == 0) && (strcmp(password, password1) == 0)) {
              printf("this's true\nPICKSIDE COMMAND: %d", PICK_SIDE);
              socket1 = fd;
              sprintf(temp, "%d", socket1);
              printf("%s\n", message_toString(message_construct(PICK_SIDE, "1", temp, "0", "0")));
              if (send(fd, message_toString(message_construct(PICK_SIDE, "1", temp, "0", "0")), MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
                printf("send() sent a different number of bytes than expected\n");
              }

            } else if((strcmp(id, id2) == 0) && (strcmp(password, password2) == 0)) {
              socket2 = fd;
              sprintf(temp, "%d", socket1);
              printf("%s\n", message_toString(message_construct(PICK_SIDE, "0", temp, "0", "0")));
              if (send(fd, message_toString(message_construct(PICK_SIDE, "0", temp, "0", "0")), MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
                printf("send() sent a different number of bytes than expected\n");
              }         
            }
            //END DEBUGGING
            else {
              printf("SEND THIS COMMAND: %d\n", FAILURE);
              if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                printf("send() sent a different number of bytes than expected\n");
              }
            }
            
          break;
          case SIGNUP:
            strcpy(id, newMesg->arg);
            printf("%s\n", id);
            strcpy(password, newMesg->arg1);
            printf("%s\n", password);
            //TODO Check account here

            if(1) {
              if (send(fd, recv_data, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
                printf("send() sent a different number of bytes than expected\n");
              }         
            }
            else {
              if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                printf("send() sent a different number of bytes than expected\n");
              }
            }

          break;
          case SIGNOUT:
            // TODO: decrease player counter
            if (send(fd, recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
              printf("send() sent a different number of bytes than expected\n");
            }
          break;
          case MOVE:          
            //TODO: play module here
              
            //FOR DEBUGGING
            if(fd == socket1) {
              printf("%d turn\n", socket1);
              //Check the port here
              if (send(socket2, recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                printf("send() sent a different number of bytes than expected\n");
              } 
            }
            else {
              printf("%d turn\n", socket1);
              if (send(socket1, recv_data, MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
                printf("send() sent a different number of bytes than expected\n");
              }
            }
            //END DEBUGGING

          break;
          default:
          printf("Error occurred\n");

          if (send(fd, message_toString( message_construct(FAILURE, "0", "0", "0", "0") ), MESSAGE_MAXLEN , 0) != MESSAGE_MAXLEN ) {
            printf("send() sent a different number of bytes than expected\n");
          }
          break;
        }

	    } 
	    else {
	      close(fd);
	      FD_CLR(fd, &fdset);  /*turn off the bit for fd in fdset*/
	      printf("Not connect client on fd %d\n", fd);
	    }
	  }
	}
      }
    }
  }
  close(serv_sockfd);
}
Beispiel #10
0
void
str_cli(int sockfd)
{
  char	*sendline, recvline[MAXLINE], ch;
  message_t newMesg, recvMesg;
  int buffrecv;

    while(1)
      {
  	ch = menu();
	switch(ch)
	  {
	  case '1':
	    printf("\n\nSIGN IN\n");
	    sendline = message_toString(getIdAndPassword(SIGNIN));
		
		if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';

	    newMesg = message_parse(recvline);
	    switch(newMesg->cmd) {
	    	case SIGNIN:
	    	printf("\nWelcome to console chess game\n");
	    	
	    	for(;;) {
	    		
	    	}


	    	mainConsoleChess(LIGHT, sockfd);
	    	break;

	    	default:
	    	printf("Fail to sign in\n");
	    	break;
	    }

	    continue;

	  case '2':
	    printf("\n\nSIGN UP\n");
	    sendline = message_toString(getIdAndPassword(SIGNUP));

	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN ) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    puts(recvline); //Debug

	    newMesg = message_parse(recvline);
	    switch(newMesg->cmd) {
	    	case SIGNUP:
	    	//printf("\nSuccessfull sign up id %s.\n", newMesg->arg);
	    	printf("\nSuccessfull sign up\n");
	    	break;
	    	default:
	    	printf("Fail to sign up. Maybe this account doesn't exist\n");
	    	break;
	    }
	    continue;

	  case '3':
	    printf("Exit\n", ch);
	    sendline = message_toString(message_construct(SIGNOUT, "0", "0", "0", "0"));
	    
	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (buffrecv = recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    puts(recvline); //Debug
	    printf("\nI'm done!\n");
	    exit(0);
	    break;

	  default:
	    printf("Wrong option! Please choose again\n");
	    continue;
	  }
	break;
      }
    printf("\n");
  
	
}
Beispiel #11
0
void
str_cli(int sockfd)
{
  char	*sendline, recvline[MAXLINE], ch;
  message_t newMesg, recvMesg;
  int buffrecv;

    while(1)
      {
  	ch = menu();
	switch(ch)
	  {
	  case '1':
	    printf("\n\nSIGN IN\n");
	    sendline = message_toString(getIdAndPassword(SIGNIN));
		
		if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    //printf("%d\n", strlen(recvline));
	    puts(recvline);
	    newMesg = message_parse(recvline);
	    printf("COMMAND: %d\nArg: %s\nArg1: %s\nOption: %s\nOption1: %s\n", newMesg->cmd, newMesg->arg, newMesg->arg1, newMesg->option, newMesg->option1);
	    puts("{ cmd : 9; arg : 1; arg1 : 5; option : 0; option1 : 0; }");
	    newMesg = message_parse("{ cmd : 9; arg : 1; arg1 : 5; option : 0; option1 : 0; }");
	    if(strcmp(recvline, "{ cmd : 9; arg : 1; arg1 : 5; option : 0; option1 : 0; }") == 0) {
	 	   printf("COMMAND: %d\nArg: %s\nArg1: %s\nOption: %s\nOption1: %s\n", newMesg->cmd, newMesg->arg, newMesg->arg1, newMesg->option, newMesg->option1);
	 	   printf("Debugging\n");
		}
	    printf("MESSAGE COMMAND: %d\n", newMesg->cmd);

	    switch(newMesg->cmd) {
	    	case PICK_SIDE:
	    	printf("\nWelcome to console chess game\n");
	    	//printf("Arg: %s\n", newMesg->arg);
	    	if(strcmp(newMesg->arg, "0") == 0) {
	    		mainConsoleChess(0, sockfd);
	    	}
	    	else if (strcmp(newMesg->arg, "1") == 0) {
	    		mainConsoleChess(1, sockfd);
	    	}

	    	break;

	    	default:
	    	printf("MESSAGE COMMAND: %d\n", newMesg->cmd);
	    	printf("Fail to sign in\n");
	    	break;
	    }

	    continue;

	  case '2':
	    printf("\n\nSIGN UP\n");
	    sendline = message_toString(getIdAndPassword(SIGNUP));

	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN ) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    puts(recvline); //Debug

	    newMesg = message_parse(recvline);
	    switch(newMesg->cmd) {
	    	case SIGNUP:
	    	//printf("\nSuccessfull sign up id %s.\n", newMesg->arg);
	    	printf("\nSuccessfull sign up\n");
	    	break;
	    	default:
	    	printf("Fail to sign up. Maybe this account doesn't exist\n");
	    	break;
	    }
	    continue;

	  case '3':
	    printf("Exit\n", ch);
	    sendline = message_toString(message_construct(SIGNOUT, "0", "0", "0", "0"));
	    
	    if (send(sockfd, sendline, MESSAGE_MAXLEN, 0) != MESSAGE_MAXLEN) {
	      printf("send() sent a different number of bytes than expected\n");
	    }

	    if (buffrecv = recv(sockfd, recvline, MESSAGE_MAXLEN, 0) < 0) {
	      printf("str_cli: server terminated prematurely\n");
	      exit(1);
	    }
	    recvline[strlen(recvline)] = '\0';
	    puts(recvline); //Debug
	    printf("\nI'm done!\n");
	    exit(0);
	    break;

	  default:
	    printf("Wrong option! Please choose again\n");
	    continue;
	  }
	break;
      }
    printf("\n");
  
	
}