Networking

Intro

Working With URLs

Opening a web page with a URL object, from Java

Using Stream Sockets

Stream sockets are used for connection-oriented communication between a client and server

Server:

  1. Create a ServerSocket object:
     ServerSocket serv = new ServerSocket(portNumber, queueLength);
    
  2. Listen for a client connection. Call method accept():
      Socket connection = serv.accept();
    
  3. Retrieve the OutputStream and InputStream objects associated with the socket:
     OutputStream os = connection.getOutputStream();
     InputStream is = connection.getInputStream();
    
    If we desire, we can wrap these up in other types of streams:
      ObjectInputStream objIn = new ObjectInputStream(is);	// etc
    
  4. Process data with the stream objects (like writing to and reading from files)
  5. close the connections by invoking the close() method on the streams and the Socket
      connection.close();
    

Client:

  1. Create a socket to connect to the server:
      Socket connection = new Socket(serverAddress, port);
    
  2. Obtain the socket's InputStream and OutputStream references (like step 3 of server)
  3. Process data
  4. Close the socket

Using Datagram Sockets


Deitel Examples