0% found this document useful (0 votes)
69 views

Java Networking: by The Java Tutorials Al/networking/overview/index - HTML

The document discusses Java networking basics including: - The java.net package provides classes for system-independent network communication using TCP and UDP. - TCP provides reliable data transmission while UDP sends independent data packets without guarantees. - URLs represent web addresses and can be used to access resources over the internet. - Sockets represent endpoints in a two-way connection and are used for client-server communication.

Uploaded by

Adele Brown
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Java Networking: by The Java Tutorials Al/networking/overview/index - HTML

The document discusses Java networking basics including: - The java.net package provides classes for system-independent network communication using TCP and UDP. - TCP provides reliable data transmission while UDP sends independent data packets without guarantees. - URLs represent web addresses and can be used to access resources over the internet. - Sockets represent endpoints in a two-way connection and are used for client-server communication.

Uploaded by

Adele Brown
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Java Networking

By The Java Tutorials


https://docs.oracle.com/javase/tutori
al/networking/overview/index.html
Networking Basics
• java.net package provides classes system-independent network
communication. However, to decide which Java classes your programs should
use, you do need to understand how TCP and UDP differ.
• TCP (Transmission Control Protocol) is a connection-based protocol that
provides a reliable flow of data between two computers. TCP provides a
point-to-point channel for applications that require reliable communications. 
• UDP (User Datagram Protocol) is a protocol that sends independent packets
of data, called datagrams, from one computer to another with no guarantees
about arrival. UDP is not connection-based like TCP.
• Through the classes in java.net, Java programs can use TCP or UDP to
communicate over the Internet. The URL, URLConnection, Socket,
and ServerSocket classes all use TCP to communicate over the network.
The DatagramPacket, DatagramSocket, and MulticastSocket classes are for
use with UDP.
Port
The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer.
Working with URLs
• URL (Uniform Resource Locator) is a reference (an address)
to a resource on the Internet. Java programs that interact
with the Internet also may use URLs to find the resources
on the Internet they wish to access. Java programs can use
a class called URL in the java.net package to represent a
URL address.
•  A URL has two main components:
Protocol identifier: For the URL http://example.com,
the protocol identifier is http.
Resource name: For the URL http://example.com, the
resource name is example.com.
Resource name
The resource name is the complete address to the resource. The format of the
resource name depends entirely on the protocol used, but for many protocols,
including HTTP, the resource name contains one or more of the following components:
• Host Name
– The name of the machine on which the resource lives.
• Filename
– The pathname to the file on the machine.
• Port Number
– The port number to which to connect (typically optional).
• Reference
– A reference to a named anchor within a resource that usually identifies a specific location
within a file (typically optional).
For many protocols, the host name and the filename are required, while the port
number and reference are optional. For example, the resource name for an HTTP URL
must specify a server on the network (Host Name) and the path to the document on
that machine (Filename); it also can specify a port number and a reference.
Creating a URL
URL myURL = new URL("http://example.com/");

URL myURL = new URL("http://example.com/pages/");


URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");

new URL("http", "example.com", "/pages/page1.html");

new URL("http", "example.com", 80,"pages/page1.html");

URI uri =
new URI("http", "example.com", "/hello world/", "");
URL url = uri.toURL();

!!! URLs are "write-once" objects. Once you've created a URL object, you cannot change
any of its attributes (protocol, host name, filename, or port number).
URL objects. Methods
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {

URL url = new URL("http://example.com:80/docs/books/tutorial"


+ "/index.html?
name=networking#DOWNLOADING");

System.out.println("protocol = " + url.getProtocol());


System.out.println("authority = " + url.getAuthority());
System.out.println("host = " + url.getHost());
System.out.println("port = " + url.getPort());
System.out.println("path = " + url.getPath());
System.out.println("query = " + url.getQuery());
System.out.println("filename = " + url.getFile());
System.out.println("ref = " + url.getRef());
} protocol = http
} authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
Reading Directly from a URL
import java.io.*;

public class URLReader {


public static void main(String[] args) throws Exception {

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

BufferedReader in =
new BufferedReader(new InputStreamReader(oracle.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Connecting to a URL

try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
Reading from a URLConnection
import java.net.*;
import java.io.*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL url = new URL("http://www.oracle.com/");
URLConnection yc = url.openConnection();
BufferedReader in =
new BufferedReader(new InputStreamReader(yc.getInputStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Writing to a URLConnection
import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse “+
"http://<location of your servlet/script>"+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

URL url = new URL(args[0]);


URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out =
new OutputStreamWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();

BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()));

String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
Socket
• A socket is one end-point of a two-way
communication link between two programs
running on the network. 
• Socket classes are used to represent the
connection between a client program and a server
program.
• The java.net package provides two classes
-Socket and ServerSocket - that
implement the client side of the connection and
the server side of the connection, respectively.
The client and server can now communicate by writing to or reading from their sockets.
Class Socket
• implements one side of a two-way connection
between your Java program and another
program on the network
• sits on top of a platform-dependent
implementation, hiding the details of any
particular system from your Java program
• instead of relying on native code, your Java
programs can communicate over the network in
a platform-independent fashion
ServerSocket class
• implements a socket that servers can use to
listen for and accept connections to clients
Reading from and Writing to a Socket
The example program implements a client, EchoClient, that connects to an echo server. The
echo server receives data from its client and echoes it back. The example EchoServer
implements an echo server. (Alternatively, the client can connect to any host that supports the
Echo Protocol.)
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try ( // try-with-resources statement
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader ( new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader ( new InputStreamReader(System.in))
)

1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's
protocol.
4. Close the streams. java EchoServer 7
5. Close the socket. java EchoClient echoserver.example.com 7
Example. EchoClient

import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Writing the Server Side of a Socket
The example program implements a client, EchoClient, that connects to an echo server. The
echo server receives data from its client and echoes it back. The example EchoServer
implements an echo server. (Alternatively, the client can connect to any host that supports the
Echo Protocol.)
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try ( // try-with-resources statement
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader ( new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader ( new InputStreamReader(System.in))
)

1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's
protocol.
4. Close the streams.
5. Close the socket.
Example. EchoServer
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);

try (
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader in =
new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Running program
java EchoServer 7
java EchoClient echoserver.example.com 7
Knock Knock Example
• https://docs.oracle.com/javase/tutorial/netw
orking/sockets/clientServer.html

You might also like