1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

GTK with tcp/ip socket: how can you do both?

Discussion in 'C' started by tjw09003, Sep 4, 2010.

  1. tjw09003

    tjw09003 New Member

    Joined:
    Sep 4, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I put together a quick program from tutorials that acts like a server listening on a socket. The program pauses on the line

    n = read(newsockfd,buffer,255);

    I wanted to add a window to this program with gtk, but I realized I don't know how to have both together. As gtk_main() also causes the program to pause...

    How can you have a gtk window and have the program listen on a socket?
    Code:
    #include <stdio.h>
    #include <sys/types.h> 
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <gtk/gtk.h>
    
    void error(char *msg)
    {
        perror(msg);
        exit(1);
    }
    
    unsigned char readSocket(){
         unsigned char temp;
         int sockfd, newsockfd, portno, clilen;
         char buffer[256];
         struct sockaddr_in serv_addr, cli_addr;
         int n;
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
         if (sockfd < 0) 
            error("ERROR opening socket");
         bzero((char *) &serv_addr, sizeof(serv_addr));
         portno = atoi("60000");
         serv_addr.sin_family = AF_INET;
         serv_addr.sin_addr.s_addr = INADDR_ANY;
         serv_addr.sin_port = htons(portno);
         if (bind(sockfd, (struct sockaddr *) &serv_addr,
                  sizeof(serv_addr)) < 0) 
                  error("ERROR on binding");
         listen(sockfd,5);
         
         for(;;){
         clilen = sizeof(cli_addr);
         newsockfd = accept(sockfd, 
                     (struct sockaddr *) &cli_addr, 
                     &clilen);
         if (newsockfd < 0) 
              error("ERROR on accept");
         bzero(buffer,256);
         n = read(newsockfd,buffer,255);
         if (n < 0) error("ERROR reading from socket");
         printf("%s",buffer);
    
         close(newsockfd);
         }
         return 0;
    
    }
    
    int main(int argc, char *argv[])
    {
       
      GtkWidget *window;
    
      gtk_init(&argc, &argv);
    
      window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
      gtk_widget_show(window);
    
      gtk_main();
    
      readSocket();  
        
         return 0; 
    }
     

Share This Page