Beruflich Dokumente
Kultur Dokumente
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
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
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
URL
Resource Name
Host Name File Name Port Number (typically optional) Reference (typically optional)
9
URL Constructors
URL
It is possible to get information about a URL object by using accessor methods Accessor Methods
13
Output of the program protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING
14
Using URLs
15
Uses openStream method of the URL class Returns a java.io.InputStream from which information can be read directly Functionality is limited
16
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
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
Create a URL Open a URLConnection Get an Input Stream from the Connection Read from the Input Stream Close the Input Stream
21
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
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
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
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
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
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
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.*;