What should we notice when one program contains both socket server and client?

42 Views Asked by At

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.

0

There are 0 best solutions below