title: Can the server use the same socket to send the response to the client? how?
body: <p>I am using Berkeley sockets (both: Internet domain and Unix domain) and I was wondering if the server can use the same sockets for reading the request and writing a response to the client. Or should the client create an other socket to wait for the replay and the server connect to it after processing the message received.</p>
  
  <p>By the way, I am talking about connection oriented sockets (stream sockets, TCP, ...).</p>
  
  <p>This is the simplified server code (I ommit error checking on system calls here just for simplicity):</p>
  
  <pre><code>int main() {
  
      int server_socket, connected_socket;
      struct sockaddr_in server_addr;
      char buf[1024];
      char aux[256];
      int bytes_read;
  
      server_socket = socket(AF_INET, SOCK_STREAM, 0);    
  
      server_addr.sin_family = AF_INET;
      server_addr.sin_addr.s_addr = INADDR_ANY;
      server_addr.sin_port = htons(1234);
      bind(server_socket, &amp;server_addr, sizeof(server_addr))
  
      listen(server_socket, 5)
  
      connected_sodket = accept(server_socket, 0, 0);
      do {
          bzero(buf, sizeof(buf));
          bytes_read = read(connected_socket, buf, sizeof(buf));        
      } while (bytes_read &gt; 0);          
  
      /* Here I want to use connected_socket to write the reply, can I? */
  
      close(connected_socket);       
  
      close(server_socket);
  
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>And this is the simplified client code (I ommit error checking on system calls here just for simplicity):</p>
  
  <pre><code>int main() {
  
      int client_socket;
      struct sockaddr_in server_addr;
  
      client_socket = socket(AF_INET, SOCK_STREAM, 0);
  
      hp = gethostbyname("myhost");
      server_addr.sin_family = AF_INET;
      memcpy(&amp;server_addr.sin_addr, hp-&gt;h_addr_list[0], hp-&gt;h_length);
      server_addr.sin_port = htons(1234);
  
      connect(client_socket, &amp;server_addr, sizeof(server_addr));
  
      write(client_socket, MSG, sizeof(MSG));
  
      /* Here I want to wait for a response from the server using client_socket, can I? */
  
      close(client_socket);
  
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>Can I use <code>connected_socket</code> in the server and <code>client_socket</code> in the client to pass a response message back? Or should I use the client address I get in the server when in "accept" to connect to a socket in the client?</p>
  
  <p>I have tried by using read/wrint in the client/server where the comment is shown but that way both programs keep blocked, it seems to be a dead-lock.</p>
  
  <p>Thanks ins advance!
  Regards.</p>