Google
 

 

up previous next contents
Up: 3. Day 3: Standard Previous: 3.2 IO: Streams and Next: 3.4 Threads   Contents

Subsections

3.3 Java networking

3.3.1 Introduction

  • Socket
  • ServerSocket
  • URL
  • URLConnection

3.3.2 Socket

  • Socket socket = new Socket(host, port);
  • server is a String or InetAddress.
  • UnknownHostException - could not convert the given host/server name to a TCP/IP address.
  • IOException - could not find server or port.
  • Methods: getInetAddress(), getPort(), getLocalPort(), getLocalAddress(), getInputStream(), getOutputStream().

3.3.3 ServerSocket

  • Listens for clients.
  • Use accept() to accept incoming connections.
    • accept returns a Socket.
    • Socket socket = serverSocket.accept();

3.3.4 ServerSocket lifecycle

  • A new ServerSocket is created on a port using a ServerSocket() constructor.
  • ServerSocket listens on the port using the accept() method.
  • Uses getInputStream() and/or getOutputStream().
  • Server and client interact using an agreed-upon communication protocol.
  • Either the server or the client (or both) close the connection.
  • The server goes back to listening with the accept() method.

3.3.5 URL

  • URL page = new URL("http://www.devdaily.com");
  • getContent()
  • openStream()
  • openConnection() - returns a URLConnection.

3.3.6 URLConnection

  • Created from a URL object using openConnection().
      URL url = new URL("http://www.devdaily.com");
      URLConnection uc = url.openConnection();
    
  • getInputStream() - read data from the server.
  • getContentType() - returns the MIME content type of the data.
  • getContentLength() - returns the number of bytes in the content.