0

I want the client to communicate with the server using TCP/IP socket connection. When the connection is accepted on the server side, the child process is created. This child process read and processes incoming data. I thought, that when I do subsequent writes from the client, on the open connection, that the server side will do forking again, if the doSomething process has already exited. However what happening is, that the 2nd client write (TEST2) writes to a socket and:

a) the write indicates no error, but the server is not receiving anything or

b) exception Broken pipe

I have the pseudo code like this:

Client socket side:
{

    socketFD = socket(AF_INET, SOCK_STREAM, 0);
    connect(socketFD, (struct sockaddr *) &serv_addr, sizeof(sockaddr));
    write(socketFD, “TEST1”, strlen(“TEST1”));
    …….
    write(socketFD, “TEST2”, strlen(“TEST2”)); // error: Broken pipe

    .....
    close(sfd);

}

Server socket side: doSomething is running on a forked child process:

void doSomething(int socket)
{  

    int n;
    const int bufferSize = 1025;
    char buffer[1025];

    bzero(buffer,bufferSize);
    n = read(sock,buffer,bufferSize-1);

}

The write for “TEST2” will fail with the message “broken pipe”. This is probably because the doSomething has finished. The question is:

  1. how can I keep the forked (child) process doSomething listen after all (TEST1) data has been received and processed by the doSomething?
  2. if I keep doSomething continuously listen, how can I stop doSomething, if the client closes connection?
Daniel Larsson
  • 527
  • 2
  • 6
  • 23
query
  • 329
  • 7
  • 18
  • 1) code the client to send a "close" command , and 2) is typically achieved with a heartbeat handshake. – newbie Nov 01 '18 at 19:52
  • I wanted to avoid closing the connection if I have ("in a while") more date to write. – query Nov 02 '18 at 00:48
  • You only need to close the connection when your finished with it ? The close message allows you to keep your server process running until the client is finished with it – newbie Nov 02 '18 at 01:00

1 Answers1

0
void doSomething(int socket)
{  

    int n;
    char buffer[1024];
    do
    {
        //Normally your process will be blocked here until it receives some data from the client.
        //The socket must be under the blocking mode;
        n = read(sock,buffer,sizeof(buffer));
        ...do something with the buffer;
    }while(n>0);
}
eprom
  • 226
  • 2
  • 11
  • The 1 st loop is OK. After that it is waiting on read, even the client made another 3 writes. – query Nov 02 '18 at 03:31
  • Part of the problem was, that the client was waiting for a server response (message). Thanks. – query Nov 02 '18 at 04:11
  • I have an open-source project which is a TCP network library based on NIO technology. You can see the modern implementations of TCP servers and clients in it. Its address is https://github.com/an-tao/trantor – eprom Nov 02 '18 at 05:05