tcp server using pthreads is not working...ne help plz?


 
Thread Tools Search this Thread
Top Forums Programming tcp server using pthreads is not working...ne help plz?
# 1  
Old 06-13-2008
tcp server using pthreads is not working...ne help plz?

Hi,

I am new to using threads in C++ though I have been wkring on C++ for past 1.5 years...I want to write a TCP server that serves multiple client connections...to start off..i have been working on a simple tcp echo server trying to understand how threads work....

this is my server code:

Code:
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <resolv.h>
#include <pthread.h>
#include <fcntl.h>
#include <netdb.h>

using namespace std;

void panic(char *msg);
#define panic(m)        {perror(m); abort();}


/*****************************************************************************
        *** This function makes the socket non-blocking!
*****************************************************************************/
void nonblock(int &sockfd)
{
        int opts;
        opts = fcntl(sockfd, F_GETFL);
        cout<<"in opt"<<endl;
        if(opts < 0)
                panic("fcntl(F_GETFL)\n")

        opts = (opts | O_NONBLOCK);
        if(fcntl(sockfd, F_SETFL, opts) < 0)
                panic("fcntl(F_SETFL)\n")

        cout<<"after opt"<<endl;
}

/*****************************************************************************/
/*** This program creates a simple echo server: whatever you send it, it   ***/
/*** echoes the message back.                                              ***/
/*****************************************************************************/
void *servlet(void *arg)                    /* servlet thread */
{       /* get & convert the data */
        int *client = (int*)arg;
        int n;
        char s[100];
        
        pthread_detach(pthread_self());

           /* proc client's requests */
        memset(s, '\0', 100);
        while( (n = (read(*client,s,100)) ) > 0 )
        {
                if (s[0] == 'Q')
                        break;
                printf("msg: %s", s);
                write(*client,s,n);
                memset(s, '\0', n);
        }

        close(*client);
        return 0;                           /* terminate the thread */
}

int main(int count, char *args[])
{       struct sockaddr_in addr;
        int sd, port;

        if ( count != 2 )
        {
                printf("usage: %s <protocol or portnum>\n", args[0]);
                exit(0);
        }

        /*---Get server's IP and standard service connection--*/
        if ( !isdigit(args[1][0]) )
        {
                struct servent *srv = getservbyname(args[1], "tcp");
                if ( srv == NULL )
                        panic(args[1]);
                printf("%s: port=%d\n", srv->s_name, ntohs(srv->s_port));
                port = srv->s_port;
        }
        else
                port = htons(atoi(args[1]));

        /*--- create socket ---*/
        sd = socket(PF_INET, SOCK_STREAM, 0);
        if ( sd < 0 )
                panic("socket");

        int on = 1;
        if ( (setsockopt(sd, SOL_SOCKET,  SO_REUSEADDR, (char *)&on, sizeof(on)) ) < 0 )
                panic("setsockoptions");

        /*--- bind port/address to socket ---*/
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = port;
        addr.sin_addr.s_addr = INADDR_ANY;                   /* any interface */
        if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
                panic("bind");

        /*--- make into listener with 10 slots ---*/
        if ( listen(sd, 10) != 0 )
                panic("listen")
        /*--- begin waiting for connections ---*/
        else
        {       int csd;
                pthread_t child;
                FILE *fp;
                cout<<"Here: "<<endl;

                while (1)                         /* process all incoming clients */
                {
                        csd = accept(sd, NULL, NULL);     /* accept connection */
                         if (csd > 0 )
                        {
                                cout<<"New connection accepted on socket : "<<csd<<endl;
        //                      nonblock(csd);
                                pthread_create(&child, 0, &servlet, &csd);       /* start thread */
                        }
                }
        }
        close(sd);
        pthread_exit(NULL);
}

But the server is behaving in a strange manner..It is able to handle just one client at a time. When i connect multiple clients to it, only the last connection gets the echo..as for the rest...the connections are neither closed nor the messages are echoed...the client just stalls!

One more observation....the last message given by previous client is echoed to the latest connection (i.e to the latest client)...and then no more echoes to the previous client..Smilie

Am i missing something here? ne help is highly appreciated...Smilie
# 2  
Old 06-16-2008
No passers-by??? Smilie
# 3  
Old 10-24-2008
i think for each thread you have to make different pthread_t child like array to store that child threads in to it...
# 4  
Old 10-24-2008
I have modified your code so that it works. In addition I removed the pthread_create() call by replacing it with a PTHREAD_CREATE_DETACHED attribute in pthread_create.
Code:
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <resolv.h>
#include <pthread.h>
#include <fcntl.h>
#include <netdb.h>

using namespace std;

void panic(char *msg);
#define panic(m)        {perror(m); abort();}

/* servlet thread - get & convert the data */
void *servlet(void *arg)
{
   int client = (int)arg;
   int n;
   char s[100];

   /* process client's requests */
   memset(s, '\0', 100);
   while( (n = (read(client,s,100)) ) > 0 ) {
      if (s[0] == 'Q')
              break;
      printf("msg: %s", s);
      write(client,s,n);
      memset(s,'\0', n);
   }

   close(client);
   pthread_exit(0);          /* terminate the thread */
}

int main(int argv, char *args[])
{
   struct sockaddr_in addr;
   int sd, port;
   int csd;
   pthread_t child;
   int on = 1;
   pthread_attr_t pattr;

   if ( argv != 2 ) {
       printf("usage: %s <protocol or portnum>\n", args[0]);
       exit(0);
   }

   /* Get server's IP and standard service connection */
   if ( !isdigit(args[1][0]) ) {
       struct servent *srv = getservbyname(args[1], "tcp");
       if ( srv == NULL )
           panic(args[1]);
       printf("%s: port=%d\n", srv->s_name, ntohs(srv->s_port));
       port = srv->s_port;
   } else
       port = htons(atoi(args[1]));

   /* create socket */
   sd = socket(PF_INET, SOCK_STREAM, 0);
   if ( sd < 0 )
       panic("socket");

   if ((setsockopt(sd, SOL_SOCKET,  SO_REUSEADDR, (char *)&on, sizeof(on)) ) < 0 )
      panic("setsockoptions");

   /* bind port/address to socket */
   memset(&addr, 0, sizeof(addr));
   addr.sin_family = AF_INET;
   addr.sin_port = port;
   addr.sin_addr.s_addr = INADDR_ANY;
   if (bind(sd,(struct sockaddr*)&addr, sizeof(addr)) != 0)
      panic("bind");

   /* set size of request queue to 10 */
   if (listen(sd, 10) < 0)
      panic("listen");

   /* set thread create attributes */
   pthread_attr_init(&pattr);
   pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_DETACHED);

   while (1) {
      cout << "Waiting for a new connection ...." << endl;
      csd = accept(sd, NULL, NULL);
      if (csd < 0)
         panic("accept");
      cout << "New connection accepted on socket: " << csd << endl;
      pthread_create(&child, &pattr, servlet, (void *)csd);
   }

   close(sd);
   exit(0);
}

# 5  
Old 10-24-2008
Thank you, for uplowding the fixed code i did have another problem and i did findout what was going wrong with my code, tnx for your code...
# 6  
Old 01-14-2009
I went through the above fixed code. I see that it works fine. I am just curious to know what was the problem with this and that u fixed here?
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Solaris

Too much TCP retransmitted and TCP duplicate on server Oracle Solaris 10

I have problem with oracle solaris 10 running on oracle sparc T4-2 server. Os information: 5.10 Generic_150400-03 sun4v sparc sun4v Output from tcpstat.d script TCP bytes: out outRetrans in inDup inUnorder 6833763 7300 98884 0... (2 Replies)
Discussion started by: insatiable1610
2 Replies

2. Solaris

TCP listner on Solaris server

Hi, I am having a solaris server. I want to start a dummy TCP listner on UNIX OS on a specific port can anyone please let me know the process. IP ADDRESS: 123.123.123.123 Port: 8010 (1 Reply)
Discussion started by: mayank2211
1 Replies

3. Programming

Concurrent TCP client/server

I made a program and now I need to make it concurrent. Can someone pls help me do this ? The code is this: #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <string.h>... (4 Replies)
Discussion started by: Johnny22
4 Replies

4. Programming

Problem with tcp server

Hello @ all, I hope you can give me some advice :b: I will be following code for a tcp server and doStuff () function, the clients treated. From some point, I have several identical clients (zombies, I think), the same records in the database write. Has anyone an explanation? What can I... (1 Reply)
Discussion started by: yumos
1 Replies

5. IP Networking

TCP server dies after few hours of inactivity

We have a NAS application which can be accessed by both HTTP and HTTPS connections. The issue we are facing is that the tcp server instance that initiates the HTTP access dies after a few hours of inactivity(the NAS application was kept idle for around 10 hours). However, the tcpserver that... (1 Reply)
Discussion started by: swatidas11
1 Replies

6. Shell Programming and Scripting

How can i hide Server Type Plz

Helo .. How Can i Hide My Server Type Here Hostpres.com - Host Pres And writing Secureb By .... And how Can i Hide uname -a: Linux server.xxxx.net 2.6.18-ovz028stab053.14-enterprise #1 SMP Mon Jun 2 18:25:30 MSD 2008 i686 From Php Shell Like c99... (3 Replies)
Discussion started by: a7medo
3 Replies

7. Programming

How to check TCP server status

Please tell me according to C/C++ socket programming; how client can check whether server is running or not during TCP communication. (1 Reply)
Discussion started by: mansoorulhaq
1 Replies

8. UNIX for Dummies Questions & Answers

Tcp-server

I have true64 Unix running and there a scales in the sytem which connect thru a com-server to the network. they have their own IP-address and are communicating over port 8000. when I telnet to the com-servers and the print function of the scale is executed I can see the data coming. I need to know... (1 Reply)
Discussion started by: albinhess
1 Replies

9. Programming

multi-threaded server, pthreads, sleep

I am trying to writa a multi-client & multi-threaded TCP server. There is a thread pool. Each thread in the pool will handle requests of multiple clients. But here I have a problem. I find a solution but it is not how it must be... i think. When threads working without sleep(1) I can't... (0 Replies)
Discussion started by: Parahat Melayev
0 Replies

10. Programming

Tcp Ip Server

i am programming a tcp_ip server which intends to listen permanently to a client . the client can disconnect and connect again and the server accept it(by this point it works).The problem is when the client lose connection without a disconnect command and my code can't get it and keeps waiting for... (4 Replies)
Discussion started by: massimo_ratti
4 Replies
Login or Register to Ask a Question