0

I'm using C on Linux.

I write a socket server program which is used to process a client's HTTP requests. When the program receives a specific request, it will connect to another HTTP server, send an HTTP request, receive the response, and then send a response to the client.

The code is like this:

......
int server=socket(...);
......(socket initialization code)
......
listen(server,1);
char buff[1024]
while(1){
    int client=accept(server,...);
    recv(client,buff,1027,0);
    if(strcmp(buff,"specific request")==0){
        int sock=socket(...);
        ......(client socket initialization code)
        connnect(sock,......);
        send(sock,......);
        recv(sock,......);
        close(sock);
    }
    send(client,......);
    close(client);
}

But it contains many problems. For example, it should run send(sock,......) three times so that recv(sock,......) would not block permanently and receive correct data.

When I separate the code like this:

......
int server=socket(...);
......(socket initialization code)
......
listen(server,1);
char buff[1024]
while(1){
    int client=accept(server,...);
    recv(client,buff,1027,0);
    send(client,......);
    close(client);
}

and

int sock=socket(...);
......(client socket initialization code)
connnect(sock,......);
send(sock,......);
recv(sock,......);
close(sock);

They can both run correctly.

I wonder how to write the expected program which has both socket server and client.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Pudron
  • 66
  • 1
  • 7
  • 2
    You can use multiple threads. – Barmar Apr 01 '21 at 01:47
  • I have tried multiple threads but it makes no effect. – Pudron Apr 01 '21 at 01:49
  • 3
    @Pudron then you are not using the threads correctly, but we can't see what you actually tried, so please [edit] your question with new details. If you don't want to use threads, then put the sockets into non-blocking mode and multiplex their I/Os in a single thread by using `select()` or `(e)poll()` in a loop to know when to read from or write to each socket. – Remy Lebeau Apr 01 '21 at 01:56
  • Server thread -> producer-consumer queue -> client thread. Yes, it will work. – Martin James Apr 01 '21 at 05:33

0 Answers0