Sie sind auf Seite 1von 40

Networking in Java

Contents

Overview of Networking Networking with Java URL and URLConnection Classes Socket Programming
2

Networking

The Java Applications that we write will be in the Application Layer The Protocols in the Transport Layer can be used, by using different classes in the java.net Package
3

TCP

Transmission Control Protocol A Connection Oriented Protocol

A Connection is established Then Data is sent along that Connection Analogous to a Telephone Call

A Reliable Protocol
Application Layer Protocols that use TCP

HTTP FTP

UDP

User Datagram Protocol A Connectionless Protocol

No Connection is established Packets are sent independently

Faster than TCP

Used in applications that do not require a lot of reliability


5

Ports

A Computer has only one Physical Connection to the Network But Data may be intended for Several Applications Ports are used to indicate which Application requires which data

Ports

The TCP and UDP Protocols use Ports to map incoming Data to a Particular Process running on a Computer

Networking in Java

Classes that use TCP

URL URLConnection Socket ServerSocket DatagramPacket DatagramSocket MulticastSocket


8

Classes that use UDP


URL

Uniform Resource Locator

A Reference to a resource on the Internet

Resource Name

Host Name File Name Port Number (typically optional) Reference (typically optional)
9

URL Constructors

Most common way is to use the absolute address of the URL


URL gamelan = new URL("http://www.gamelan.com/");

URL objects can be created relative to a common base URL

URL gamelan = new URL("http://www.gamelan.com/pages/"); URL gamelanGames = new URL(gamelan, "Gamelan.game.html");

Can also be created by providing different parts of the URL seperately


10 new URL("http", "www.gamelan.com", "/pages/Gamelan.net.html");

URL

A MalformedURLException is thrown if the arguments refer to a null or unknown protocol.


try { URL myURL = new URL(. . .) } catch (MalformedURLException e) { . . . // exception handler code here . . . }

URLs are write-once objects


11

URL Accessor Methods

It is possible to get information about a URL object by using accessor methods Accessor Methods

getProtocol() getHost() getPort() getFile() getRef()


12

URL Accessor Methods


import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL("http://java.sun.com:80/docs/books/" + "tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); } }

13

URL Accessor Methods

Output of the program protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING
14

Using URLs

Methods of using URLs

Reading directly from the URL By creating a URLConnection

15

Reading directly from the URL

Uses openStream method of the URL class Returns a java.io.InputStream from which information can be read directly Functionality is limited

16

Reading directly from the URL


import java.net.*; import java.io.*; import java.util.*; public class URLReader { public static void main(String[] args) throws Exception { URL url = new URL("http://www.yahoo.com/"); // Create URL Scanner in = new Scanner( new InputStreamReader(url .openStream())); // Open Stream String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } 17 }

Proxy Settings

If a proxy server is used programs will generate errors Run time settings have to be changed to provide details of the proxy server
java -Dhttp.proxyHost=proxyhost -Dhttp.proxyPort=portNumber URLReader

18

Creating a URLConnection

If a URL is successfully created, we can connect to the URL by using its openConnection() method

Returns an Object of type, URLConnection


Throws an IOException if the Connection cannot be opened Provides more functionality
19

Creating a URLConnection
try { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yahooConnection = yahoo.openConnection(); } catch (MalformedURLException e) { // new URL() failed . . . } catch (IOException e) { // openConnection() failed . . . }

20

URLConnection Reading from a URL

To Read from a URLConnection

Create a URL Open a URLConnection Get an Input Stream from the Connection Read from the Input Stream Close the Input Stream

21

URLConnection Reading from a URL


import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); Scanner in = new Scanner(yc.getInputStream()); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
22

URLConnection Writing to a URL

Instances when writing to a URL is necessary in HTTP


Filling forms Using server side scripting Create a URL Open a URLConnection Set output capability on the URLConnection Get an Output Stream from the Connection Write to the Output Stream Close the Output Stream
23

To Write to a URLConnection

URLConnection Writing to a URL

The backward cgi script available in http://java.sun.com/cgi-bin/backwards reads in a string from the standard input, reverses it and writes the result back to the standard output Used to test the functionality of writing to a URL

24

URLConnection Writing to a URL


import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception {

String stringToReverse = URLEncoder.encode("String to reverse"); URL url = new URL("http://java.sun.com/cgi-bin/backwards"); URLConnection connection = url.openConnection(); connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("string=" + stringToReverse); out.close();

25

URLConnection Writing to a URL


BufferedReader in = new BufferedReader( newInputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }
}
26

Sockets

URL & URLConnection provide a High Level mechanism for accessing resources on the web For Lower Level interaction we have to use Sockets

Eg.- Client-Server Applications

27

Sockets

A Socket is one endpoint of a two-way Communication Link between two Programs running on the Network It is bound to a Port Number so that the TCP layer can identify the Application that Data is to be sent to.

28

Sockets

The Server listens to a Port to see if any requests are made

ServerSocket

The Client requests to connects to the Server on the particular port If the Server accepts, a connection is made

Socket

The Client and Server can now communicate by Writing to or Reading from their Sockets
29

Sockets

Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close the streams. Close the socket.

30

Sockets Client
import java.net.*; import java.io.*; Socket s = new Socket("this.doesnt.exist.com", 1024); BufferedReader in = new BufferedReader( new InputStreamReader(s.getInputStream())); PrintStream out = new PrintStream(s.getOutputStream());

31

EchoClient

Echo server is a well-known service that listens to client requests on port no 7 It receives data from a client and echoes them back EchoClient creates a socket thereby getting a connection to the Echo server It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket
32

EchoClient

The server echoes the input back through the socket to the client The client program reads and displays the data passed back to it from the server

33

EchoClient
import java.io.*; import java.net.*;
public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; /* establish the connection with the server and get input and output streams */

34

EchoClient
try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); }
35

EchoClient
BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }
36

Sockets - Server

import java.net.*; SeverSocket sSoc = new ServerSocket(1024); Socket in = sSoc.accept();

Port Numbers below 1024 should not be used because they are reserved for Well-Known Services

37

Datagrams

A Datagram is an independent, self-contained message sent over the network It uses UDP

The arrival, arrival time, and content of a Datagram are not guaranteed.

38

Datagrams - Client

import java.net.*;
public class SenderGram { public static void main(String ar[]) { try { if (ar.length != 1) { System.exit(1); } InetAddress ia=InetAddress.getByName("LocalHost"); DatagramSocket ds=new DatagramSocket(); byte buffer[]=ar[0].getBytes(); DatagramPacket dp=new DatagramPacket(buffer, buffer.length, ia, 2495); ds.send(dp); } catch(Exception e) { } } }
39

Datagrams - Server

import java.net.*;

public class ReceiverGram {


public static void main(String ar[]) { try { DatagramSocket ds=new DatagramSocket(2495); byte buffer[]=new byte[20]; while (true) { DatagramPacket dp=new DatagramPacket(buffer, buffer.length); ds.receive(dp); String str=new String(dp.getData()); System.out.println(str); } } catch(Exception e) { } } }
40

Das könnte Ihnen auch gefallen