Sei sulla pagina 1di 18

Java Networking

Sergio Luján Mora

Departamento de Lenguajes y
Sistemas Informáticos

Contents
• Java networking?
• Networking basics
• Networking classes in JDK
• Parsing a URL
• Sockets
• Example

1
Java networking
• The Java platform is very famous in part
because of its suitability for writing
programs that use and interact with
the resources on the Internet and the
World Wide Web
• Java-compatible browsers use this
ability of the Java platform to the
extreme to transport and run applets
over the Internet

Networking basics
• Computers running on the Internet communicate to each other
using either the Transmission Control Protocol (TCP) or the
User Datagram Protocol (UDP)
• When you write Java programs that communicate over the
network, you are programming at the application layer
• To decide which Java classes your programs should use, you
do need to understand how TCP and UDP differ

2
Networking basics
• TCP
– TCP guarantees that data sent from one end of
the connection actually gets to the other end and
in the same order it was sent
• Otherwise, an error is reported
– TCP provides a point-to-point channel for
applications that require reliable communications
– The Hypertext Transfer Protocol (HTTP), File
Transfer Protocol (FTP), and Telnet are all
examples of applications that require a reliable
communication channel

Networking basics
• UDP
– The UDP protocol provides for communication that
is not guaranteed between two applications on the
network
– Rather, it sends independent packets of data,
called datagrams, from one application to another
– The order of delivery is not important and is not
guaranteed, and each message is independent of
any other

3
Networking basics
• Ports
– Data transmitted over the Internet is accompanied
by addressing information that identifies the
computer and the port for which it is destined
• The computer is identified by its 32-bit IP address, which
IP uses to deliver data to the right computer on the
network
• Ports are identified by a 16-bit number, which TCP and
UDP use to deliver the data to the right application on the
computer

Networking basics

4
Networking basics
• Ports
– Port numbers range from 0 to 65,535 because
ports are represented by 16-bit numbers
– The port numbers ranging from 0 – 1,023 are
restricted; they are reserved for use by well-known
services such as HTTP and FTP and other system
services
• These ports are called well-known ports
• Your applications should not attempt to bind to them

Networking basics
• Examples of well-known ports:
– Domain Name System (DNS): 53
– File Transfer Protocol (FTP): 21
– Hypertext Transfer Protocol (HTTP): 80
– Network News Transfer Protocol (NNTP):
119
– Post Office Protocol (POP3): 110
– Simple Mail Transfer Protocol (SMTP): 25
– Telnet: 23

5
Networking classes in JDK
• java.net provides the classes for implementing
networking applications
• java.net package can be roughly divided in two
sections:
– A Low Level API, which deals with the following abstractions:
• Addresses, which are networking identifiers, like IP addresses.
• Sockets, which are basic bidirectional data communication
mechanisms.
• Interfaces, which describe network interfaces.
– A High Level API, which deals with the following
abstractions:
• URIs, which represent Universal Resource Identifiers.
• URLs, which represent Universal Resource Locators.
• Connections, which represents connections to the resource
pointed to by URLs.

Networking classes in JDK


• Sockets:
– TCP: Socket, and ServerSocket
classes
– UDP: DatagramPacket,
DatagramSocket, and
MulticastSocket classes

6
Networking classes in JDK
• High level API:
– URL is the class representing a Universal
Resource Locator
– URLConnection is created from a URL and is the
communication link used to access the resource
pointed by the URL
• This abstract class will delegate most of the work to the
underlying protocol handlers like http or ftp.
– HttpURLConnection is a subclass of
URLConnection and provides some additional
functionalities specific to the HTTP protocol

Parsing a URL
• URL (Uniform Resource Locator) is a
reference (an address) to a resource on
the Internet
• Java programs can use a class called
URL in the java.net package to
represent a URL address

7
Parsing a URL
• The URL class provides several methods that
let you query URL objects:
– getProtocol()
• Returns the protocol identifier component of the URL.
– getAuthority()
• Returns the authority component of the URL.
– getHost()
• Returns the host name component of the URL.
– getPort()
• Returns the port number component of the URL.
• The getPort method returns an integer that is the port
number. If the port is not set, getPort returns -1.

Parsing a URL
• The URL class provides several methods that
let you query URL objects:
– getPath()
• Returns the path component of this URL.
– getQuery()
• Returns the query component of this URL.
– getFile()
• Returns the filename component of the URL.
• The getFile method returns the same as getPath, plus
the concatenation of the value of getQuery, if any.
– getRef()
• Returns the reference component of the URL.

8
Parsing a URL
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?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}

Parsing a URL
protocol = http
authority = java.sun.com:80
host = java.sun.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename =
/docs/books/tutorial/index.html?name=ne
tworking
ref = DOWNLOADING

9
Parsing a URL
• You can call the URL's openStream()
method to get a stream from which you can
read the contents of the URL
• The openStream() method returns a
java.io.InputStreamobject, so reading
from a URL is as easy as reading from an
input stream
• This method is a shorthand for:
openConnection().getInputStream()

Parsing a URL
import java.net.*;
import java.io.*;

public class URLReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://localhost/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(inputLine);

in.close();
}
}

10
Sockets
• In client-server applications:
– The server provides some service, such as
processing database queries or sending
out current stock prices
– The client uses the service provided by the
server, either displaying database query
results to the user or making stock
purchase recommendations to an investor

Sockets
• Server:
1. Open a server socket
2. Wait for a client
3. Accept the connection Æ Open a new socket for
the client
1. Open an input stream and output stream to the socket
for the client.
2. Read from and write to the stream according to the
server's protocol.
3. Close the streams.
4. Close the socket for the client.

11
Sockets
• Client:
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.

Sockets
• java.net package:
– ServerSocket class: implements a socket that
servers can use to listen for and accept
connections to clients
– new ServerSocket(int port)
• Creates a server socket, bound to the specified port
– new ServerSocket(int port, int
backlog)
• Creates a server socket and binds it to the specified local
port number, with the specified backlog
• The maximum queue length for incoming connection
indications (a request to connect) is set to the backlog
parameter
• If a connection indication arrives when the queue is full,
the connection is refused

12
Sockets
• java.net package:
– Socket class: implements one side of a
two-way connection between your Java
program and another program on the
network
– new Socket(String host, int
port)
• Creates a stream socket and connects it to the
specified port number on the named host

Sockets
• On the server side:
– A server runs on a specific computer and has a socket that
is bound to a specific port number
– The server just waits, listening to the socket for a client to
make a connection request

13
Sockets
// Create a new service at a port
ServerSocket servsock = new ServerSocket(4444);

while (true) {
// Wait for the next client connection
// Blocks until a client connects
Socket sock= servsock.accept(); // Listen

// handle connection
. . .
. . .
}

Sockets
• On the client side:
– The client knows the hostname of the machine on which the
server is running and the port number on which the server is
listening
– To make a connection request, the client tries to connect
with the server on the server's machine and port
– The client also needs to identify itself to the server so it binds
to a local port number that it will use during this connection
(this is usually assigned by the system)

14
Sockets
// Connect to a Service at a site.
Socket sock = new Socket("hostNameOrAddr", 4444);

Sockets
• On the server side:
– If everything goes well, the server accepts the connection
– Upon acceptance, the server gets a new socket bound to the
same local port and also has its remote endpoint set to the
address and port of the client
– It needs a new socket so that it can continue to listen to the
original socket for connection requests while tending to the
needs of the connected client

15
Sockets
// Create a new service at a port
ServerSocket servsock = new ServerSocket(4444);

while (true) {
// Wait for the next client connection, blocks until a client connects
Socket sock= servsock.accept(); // Listen

// Get I/O streams from the socket


in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintStream(sock.getOutputStream());

// Get initial string


String fromServer = in.readLine();
String reply = ...
...
out.println(reply);
out.flush(); // Writes any buffered output to the output stream
...
// Close everything
in.close();
out.close();
}

Sockets
• On the client side:
– If the connection is accepted, a socket is successfully
created and the client can use the socket to communicate
with the server

16
Sockets
// Connect to a Service at a site.
Socket sock = new Socket("hostNameOrAddr", 4444);

// Get I/O streams from the socket


in = new BufferedReader(new InputStreamReader (
sock.getInputStream()));
out = new PrintStream(sock.getOutputStream() );

// Get initial string


String fromServer = in.readLine();
String reply = ...
...
out.println(reply);
out.flush(); // Writes any buffered output to the output stream
...
// Close everything
in.close();
out.close();

Sockets
• Either server or client terminates the
connection:

sock.close();

17
Examples
• Reverse strings
• Echo service
• Chat application

18

Potrebbero piacerti anche