Google Search

Sunday, October 30, 2011

ECHO SERVER-CLIENT TCP


AIM: ECHO SERVER-CLIENT TCP

THEORY:
          The server does is wait for a connection, then uses the Socket produced by that connection to create an InputStream and OutputStream. After that, everything it reads from the InputStream it echoes to the OutputStream until it receives the line END, at which time it closes the connection.
            The client makes the connection to the server, then creates an OutputStream. Lines of text are sent through the OutputStream. The client also creates an InputStream to hear what the server is saying (which, in this case, is just the words echoed back). Both the server and client use the same port number and the client uses the local loopback address to connect to the server on the same machine so you don’t have to test it over a network.

             You can see that the ServerSocket just needs a port number, not an IP address (since it’s running on this machine!). When you call accept( ), the method blocks until some client tries to connect to it. That is, it’s there waiting for a connection but other processes can run . When a connection is made, accept( ) returns with a Socket object representing that connection. 
     
              If the ServerSocket constructor fails, the program just quits (notice we must assume that the constructor for ServerSocket doesn’t leave any open network sockets lying around if it fails). For this case, main( ) throws IOException so a try block is not necessary.
      
             If accept( ) fails, then we must assume that the Socket doesn’t exist or hold any resources, so it doesn’t need to be cleaned up. If it’s successful, however, the following statements must be in a try-finally block so that if they fail the Socket will still be cleaned up.
 

ALGO:
          SERVER SIDE

  1. Create the server socket and begin listening.
  2. Call the accept() method to get new connections.
  3. Create input and output streams for the returned socket.
  4. Conduct the conversation based on the agreed protocol.
  5. Close the client streams and socket.
  6. Go back to step 2 or continue to step 7.
  7. Close the server socket.
CLIENT  SIDE
  1. Create the client socket connection.
  2. Acquire read and write streams to the socket. 

0 comments:

Post a Comment