示例#1
0
文件: socket.cpp 项目: Angeldude/pd
int Stream::Read(SOCKET fd,char *buf,int size,int timeout)
{
	// check for data availability so that recv doesn't block
	if(CheckForData(fd,timeout)) {
		int ret = recv(fd,buf,size, 0);
		if(ret == SOCKET_ERROR) {
			post("socket error!");
			return -1;
		}
		else
			return ret;
	}
	else
		return 0;
}
示例#2
0
文件: uts.c 项目: zhyage/C_DataStruct
int main(int argc, char **argv)
 { 
  int sockfd=0;  
  int new_fd=0;  
  struct sockaddr_in my_addr; 
  struct sockaddr_in their_addr; 
  socklen_t sin_size=0;
  char data[255]={0};
  char *endp;

  FILE *fp;
  char Filename[FILENAME_MAX] = DEFAULT_FILE_NAME;
  unsigned long currenttotal = 0;
  unsigned long  newtotal = 0;
  if(argc < 2)
  {
    printf("No file specified. Using \"%s\"\n", DEFAULT_FILE_NAME);
  }
  else
  {
    strcpy(Filename, argv[1]);
  }

  fp = fopen(Filename, "r");
  if(fp != NULL)
  {
    if(NULL != fgets(data, sizeof data, fp))
    {
      currenttotal = strtoul(data, &endp, 10);
    }

    fclose(fp);
  }
  else
  {
    printf("Couldn't read file %s\n", Filename);
  }

  if(signal(SIGINT, SIG_IGN) != SIG_IGN)
   {
    signal(SIGINT, inthandler);
   }

  if(signal(SIGTERM, SIG_IGN) != SIG_IGN)
   {
    signal(SIGTERM, inthandler); 
   }

  my_addr.sin_family = AF_INET;   
  my_addr.sin_addr.s_addr = INADDR_ANY; 
  my_addr.sin_port = htons(1091); 

  memset(my_addr.sin_zero, 0,sizeof my_addr.sin_zero);  

  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 
   {
    printf("Unexpected error on socket().\n");
    return EXIT_FAILURE; 
   }

  if (bind(sockfd,(struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1) 
  {
   printf("Unexpected error on bind()\n");
   return EXIT_FAILURE;
  }

  if (listen(sockfd, 4) == -1) 
   {
    printf("Unexpected error on listen()\n");
    shutdown(sockfd,2);
    return EXIT_FAILURE; 
   }



   while(!done) 
    {  
     if(0 != CheckForData(sockfd))
     {
     sin_size = sizeof(struct sockaddr_in);
     if ((new_fd = accept(sockfd,(struct sockaddr *) &their_addr, &sin_size)) == -1) 
      {
       printf("Unexpected error on accept()\n");
       continue;
      }
      
     memset(data, 0, sizeof data);

     if (recv(new_fd, data, sizeof data, 0) == -1) 
      {
       printf("Unexpected error on recv()\n");
      }        
      else
      {
        newtotal += strtoul(data, &endp, 10);
        printf("Received data: %s\n", data);
      }
     sprintf(data, "%lu\n", currenttotal);
     if (send(new_fd, data, sizeof data, 0) == -1) 
      {
       printf("Unexpected error on send()\n");
      }        
      shutdown(new_fd, 2);
    }
  }
  shutdown(sockfd,2);
  printf("User requested program to halt.\n");
  fp = fopen(Filename, "w");
  if(fp != NULL)
  {
    fprintf(fp, "%lu\n", newtotal);
    fclose(fp);
  }
  else
  {
    printf("Couldn't write total %lu to file %s\n", newtotal, Filename);
  }
  
  return EXIT_SUCCESS; 
}
示例#3
0
PRIVATE void 
talk ()
{
  char *line;
  char *machine;
  int connection;
  int code;
  int value;
  access *Data;
  unsigned short port;

  Data = (access *) space (sizeof (access));

  printf ("enter machine to connect to (return if same as caller)\n");
  line = get_line (stdin);
  if (*line == '\0')
    {
      machine = NULL;
      free (line);
    }
  else
      machine = line;

  printf ("enter port number (return if 5000)\n");
  line = get_line (stdin);
  if (*line == '\0')
      port = 5000;
  else
      sscanf (line, "%u", port);
  free (line);

  while (TRUE)
    {
      if ((connection = DialServer (machine, port)) > 0)
	{
	  system ("clear");
	  while (CheckForData (connection, Data, sizeof (access)) <= 0);
	  show_options (Data);

	  line = get_line (stdin);
	  if (*line == '\0')
	    {
	      Send (connection, Data, sizeof (access));
	      free (line);
	    }
	  else if (*line == '\\')
	    {
	      Data->ctrl = -1;
	      if ((connection = DialServer (machine, port)) > 0)
		Send (connection, Data, sizeof (access));
	      HangUp (connection);
	      free (line);
	      free (machine);
	      exit (0);
	    }
	  else
	    {
	      sscanf (line, "%d %d", &code, &value);

	      switch (code)
		{
		case 0:
		  if (value == 2)
		    {
		      printf ("re-read parameters? (y/n) [y]\n");
		      line = get_line (stdin);
		      if (!(*line == 'y' || *line == '\0'))
			{
			  free (line);
			  Data->ctrl = 1;
			  break;
			}
		      printf ("input filename [alchemy.inp]\n");
		      line = get_line (stdin);
		      if (*line == '\0')
			strcpy (Data->message, "alchemy.inp");
		      else
			strcpy (Data->message, line);
		      free (line);
		    }
		  Data->ctrl = value;
		  break;
		  
		case 1:
		  Data->show = value;
		  break;
		  
		default:
		  printf ("no such parameter\n");
		  break;
		}
	      free (line);

	      Send (connection, Data, sizeof (access));
	    }
	}
    }
}
示例#4
0
int main(int argc, char **argv)
 { 
  WORD wVersionRequested = MAKEWORD(1,1);
  WSADATA wsaData;
  SOCKET	sock;
  SOCKADDR_IN   my_addr;
  SOCKADDR_IN   their_addr;
  int address_length;
  char data[32]= {0};
  int celc=0;
  int farh=0;


  if(signal(SIGINT, SIG_IGN) != SIG_IGN)
   {
    signal(SIGINT, inthandler);
   }

  if(signal(SIGTERM, SIG_IGN) != SIG_IGN)
   {
    signal(SIGTERM, inthandler); 
   }

  my_addr.sin_family = AF_INET;
  my_addr.sin_addr.s_addr = INADDR_ANY;	
  my_addr.sin_port = htons(1092);		

 
  WSAStartup(wVersionRequested, &wsaData);
  if (wsaData.wVersion != wVersionRequested)
   {	
    printf("\n Wrong version of Winsock\n");
    return EXIT_FAILURE;
   }

   
  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
   {
    printf("Unexpected error on socket()");
    return EXIT_FAILURE;
   }
   


  if (bind(sock, (LPSOCKADDR)&my_addr,sizeof(struct sockaddr)) == SOCKET_ERROR)
   {
    printf("Unexpected error on bind()");
    shutdown(sock,2);
    return EXIT_FAILURE;
   }

  address_length = sizeof(struct sockaddr);

  
  while(!done) 
  {  
   if(0 != CheckForData(sock))
   {
    memset(data, 0, sizeof data);

	if (recvfrom(sock, data, 
		         sizeof data, 
		         0,   (struct sockaddr *)&their_addr, 
		         &address_length) == SOCKET_ERROR) 
	{
     printf("Error on recvfrom\n");  
	}
  

    celc=atoi(data);
	farh=(celc*2)+32;
    
	memset(data, 0, sizeof data);
	
	sprintf(data, "%d", farh);
        
   if (sendto(sock, data, strlen(data), 0, 
	         (struct sockaddr *)&their_addr, 
			 sizeof(struct sockaddr)) == SOCKET_ERROR) 
   {
    printf("Error on sendto\n");  
   }
  
	printf("%s\n", data);	   

   
   
   }    
  }



   shutdown(sock,2);
   WSACleanup();
   printf("User requested program to halt.\n");
   
   return EXIT_SUCCESS; 
}
示例#5
0
文件: socket.cpp 项目: Angeldude/pd
SOCKET Stream::Connect(const char *hostname,const char *mountpoint,int portno)
{
	const int STRBUF_SIZE = 1024;
	char request[STRBUF_SIZE]; // string to be sent to server
	sockaddr_in server;
  
	SOCKET sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sockfd == SOCKET_ERROR) {
		throw "Error opening socket";
	}
  
	// get IP address
	hostent *hp = gethostbyname(hostname);
	if(!hp) {
		closesocket(sockfd);
		throw "Could not get IP address of hostname";
	}

	server.sin_family = AF_INET;
	memcpy(&server.sin_addr,hp->h_addr, hp->h_length);
	server.sin_port = htons((unsigned short)portno);
	  
	// try to connect
	if (connect(sockfd, (struct sockaddr *) &server, sizeof (server)) == SOCKET_ERROR) {
		closesocket(sockfd);
		throw "Connection failed!";
	}
  
	// check if we can read from the socket
	{
		fd_set fdset;
		FD_ZERO(&fdset);
		FD_SET(sockfd,&fdset);

		timeval  tv;
		tv.tv_sec  = 0;
		tv.tv_usec = 500;
		  
		int ret = select((int)sockfd + 1, &fdset, NULL, NULL, &tv);
		if(ret < 0) {
			closesocket(sockfd);
			throw "Can not read from socket";
		}
	}
	  
	// build up stuff we need to send to server
	sprintf(request, "GET /%s HTTP/1.0 \r\nHost: %s\r\nUser-Agent:   0.2\r\nAccept: audio/x-ogg\r\n\r\n", mountpoint, hostname);

	// try to contact server
	if(send(sockfd, request, (int)strlen(request), 0) == SOCKET_ERROR) {
		closesocket(sockfd);
		throw "Could not contact server";
	}
  
	// read first line of response
	int cnt = 0,i = 0;
	while(i < STRBUF_SIZE-1) {
		if( CheckForData(sockfd) ) {
			if(recv(sockfd, request+i, 1, 0) <= 0) {
				closesocket(sockfd);
				throw "Could not read from socket, quitting";
			}

			if(request[i] == '\n') break;
			if(request[i] != '\r') i++;

            cnt = 0;
		}
        else 
            if(++cnt > 100) {
    			closesocket(sockfd);
                throw "Read error, quitting";
            }
	}

	request[i] = '\0';
  
	bool eof = false;

	// parse content of the response...
	if(strstr(request, "HTTP/1.0 200 OK"))    /* server is ready */
    {
		//post(" : IceCast2 server detected");

		while(!eof) {
			cnt = 0,i = 0;
			while(i < STRBUF_SIZE-1) {
				if( CheckForData(sockfd) ) {
					if(recv(sockfd, request + i, 1, 0) <= 0) {
						closesocket(sockfd);
						throw "Could not read from socket, quitting";
					}

					if(request[i] == '\n')  /* leave at end of line */
						break;
					if(request[i] == 0x0A)  /* leave at end of line */
						break;
					if(request[i] != '\r')	/* go on until 'return' */
						i++;

                    cnt = 0;
				}
                else 
                    if(++cnt > 100) {
    			        closesocket(sockfd);
                        throw "Read error, quitting";
                    }
			}

			// make it a null terminated string
			request[i] = '\0';	

#if 0
			char *sptr;
			if( ( sptr = strstr(request, "application/x-ogg") ) ) {		
				/* check for content type */
				//post(" : Ogg Vorbis stream found");
			}

			if( ( sptr = strstr(request, "ice-name:") ) ) {		
				/* display ice-name */
				//post(" : \"%s\"", sptr + 10);
			}
#endif

			if(i == 0) 
				// we got last '\r\n' from server
				eof = true;	
		}
	}
	else if(strstr(request, "HTTP/1.0 404")) {
		// file not found
		closesocket(sockfd);
		throw "File not found";
	}
	else {
		// wrong server or wrong answer
		closesocket(sockfd);
		throw request;
    }

	//post(" : connected to http://%s:%d/%s", hp->h_name, portno, mountpoint);

	return sockfd;
}
示例#6
0
void run_star_demo(void)
{
    #if defined(PROTOCOL_STAR)
        t1 = MiWi_TickGet();
        LCDDisplay((char *)"Sleeping!!", 0, false);
        while(1)
        {
           
            t2 = MiWi_TickGet();    // Calculate the Time for Sleeping device

            if((MiWi_TickGetDiff(t2,t1) > (ONE_SECOND * 20)))
            {
              awake = true;
              #if !defined(EIGHT_BIT_WIRELESS_BOARD)
              LCD_BacklightON();
              #endif
      
              MiApp_TransceiverPowerState(POWER_STATE_WAKEUP_DR);
              LCDDisplay((char *)"Woke Up!!!", 0, false);
              DELAY_ms(1000);
              STAR_DEMO_OPTIONS_MESSAGE (false);
              tt1 = MiWi_TickGet();  
            }
            while(awake)   
            {
                tt2 = MiWi_TickGet();    
                if((MiWi_TickGetDiff(tt2,tt1) > (ONE_SECOND * 10)))   
                {
                    // The Indirect Message for a Sleeping RFD is stored in PAN CO 
                    // We periodically send Data Requests for the Indirect Message to 
                    // not loose a message. 
                    CheckForData();
                    tt1 = MiWi_TickGet();
                }    
                /*******************************************************************/
                // Function MiApp_MessageAvailable returns a boolean to indicate if 
                // a packet has been received by the transceiver. If a packet has 
                // been received, all information will be stored in the rxFrame, 
                // structure of RECEIVED_MESSAGE.
                /*******************************************************************/

                if( MiApp_MessageAvailable())
                {

                    /*******************************************************************/
                    // If a packet has been received, update the information available 
                    // in rxMessage.
                    /*******************************************************************/
                    DemoOutput_UpdateTxRx(TxNum, ++RxNum);
                    DELAY_ms(2000);
                    // Toggle LED2 to indicate receiving a packet.
                    LED_2 ^= 1;

                    /*******************************************************************/
                    // Function MiApp_DiscardMessage is used to release the current 
                    //  received packet.
                    // After calling this function, the stack can start to process the
                    //  next received frame 
                    /*******************************************************************/        
                    MiApp_DiscardMessage();



                    /****************************************/
                }
                else
                {
                    /*******************************************************************/
                    // If no packet received, now we can check if we want to send out
                    // any information.
                    // Function ButtonPressed will return if any of the two buttons
                    // has been pushed.
                    /*******************************************************************/
                    uint8_t PressedButton = ButtonPressed();
                    if ( PressedButton == 1 || PressedButton == 2)
                    {
                        
                        uint8_t select_ed =0;
                        bool update_ed = true;
                        while(update_ed == true)
                        {

                            //User Selected Change end device
                            LCD_Erase();
                            if (myConnectionIndex_in_PanCo  == select_ed)
                            {   // if END_device displays itself , "me" is added in display to denote itself 
                                sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x-me",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            }
                            else
                            {
                                sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            }
                            sprintf((char *)LCDText, (char*)"RB0:%02d-%02x%02x%02x",END_DEVICES_Short_Address[select_ed].connection_slot,END_DEVICES_Short_Address[select_ed].Address[0],
                                        END_DEVICES_Short_Address[select_ed].Address[1],END_DEVICES_Short_Address[select_ed].Address[2] );
                            sprintf((char *)&(LCDText[16]), (char*)"RB2: Change node");
                            LCD_Update();
                            chk_sel_status = true;
                            bool sw_layer_ack_status , mac_ack_status;
                            while(chk_sel_status)
                            {
                                uint8_t switch_val = ButtonPressed();
                                if(switch_val == 1)
                                {
                                    update_ed = false;
                                    chk_sel_status = false;
                                    update_ed = false;
                                    // Star_User_Data is defined in star_demo.c 
                                    // Its user data  , in case of Star Network 60 bytes of 
                                    // Data can be sent at a time from one END_DEVICE_TO_ANOTHER 
                                    // Edx --> Pan CO --> EDy
                                    if (myConnectionIndex_in_PanCo == select_ed)
                                    {
                                        MiApp_FlushTx();
                                        for (i = 0 ; i < 21 ; i++)
                                        {
                                            MiApp_WriteData(MiWi[(TxSynCount%6)][i]);
                                        }

                                        // IF on the demo , a END_Device displays its own Connection Detail
                                        // We unicast data packet to just PAN COR , No forwarding
                                        #if defined(ENABLE_SECURITY)
                                            mac_ack_status = MiApp_UnicastConnection (0, true);
                                        #else
                                            mac_ack_status = MiApp_UnicastConnection (0, false);
                                        #endif
                                            TxNum++;
                                    }
                                    else
                                    {
                                        // Data can be sent at a time from one END_DEVICE_TO_ANOTHER 
                                        // Edx --> Pan CO --> EDy
                                        // To forward a Packet from one ED to another ED , the first 4 bytes should holding
                                        // a CMD and end dest device short address (3 bytes)
                                        MiApp_FlushTx();
                                        MiApp_WriteData(CMD_FORWRD_PACKET);
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[0]);// sending the first byte payload as the destination nodes
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[1]);// sending the first byte payload as the destination nodes
                                        MiApp_WriteData(END_DEVICES_Short_Address[select_ed].Address[2]);// sending the first byte payload as the destination nodes
                                        for (i = 4 ; i < 25 ; i++)
                                        {
                                            MiApp_WriteData(MiWi[(TxSynCount%6)][i-4]);
                                        }
                                        #if defined(ENABLE_SECURITY)
                                            sw_layer_ack_status = MiApp_UnicastStar (true);
                                        #else
                                            sw_layer_ack_status = MiApp_UnicastStar (false);
                                        #endif


                                        #if defined(ENABLE_APP_LAYER_ACK)
                                            if (sw_layer_ack_status)
                                            {
                                                TxNum++;     // Tx was successful
                                            }
                                            else
                                            {
                                                LCDDisplay((char *)"Data_Sending_Fail!!", 0, false); 
                                            }
                                        #else    
                                            TxNum++;
                                        #endif

                                    }

                                } // end of switch_val == 1
                                else if(switch_val == 2)
                                {
                                    if (select_ed > end_nodes-1)
                                    {    
                                        select_ed = 0;
                                    }
                                    else
                                    {
                                        select_ed = select_ed+1;
                                    }
                                    chk_sel_status = false;

                                } // end of switch_val == 2
                            }  // end of chk_sel_status

                        } // end of updating the LCD info
                        STAR_DEMO_OPTIONS_MESSAGE (false);
                    } // end of actions on button press
                } // end of check for user inputs (button press check)

                t3 = MiWi_TickGet();
                if((MiWi_TickGetDiff(t3,t2) > (ONE_SECOND * 40)))
                {
                    awake = false;
                    #if !defined(EIGHT_BIT_WIRELESS_BOARD)
                              LCD_BacklightOFF();
                    #endif
                    MiApp_TransceiverPowerState(POWER_STATE_SLEEP);
                    LCDDisplay((char *)"Sleeping!!!", 0, false);
                    DELAY_ms(1000);
                    t1 = t3;

                }
                
                if (lost_connection && !role)
                {
                    MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);
                    lost_connection = false;

                }

            }  // end of actions performed while node is awake
            
           

            
        } // end of while(1)
    #endif
}