Rangkaian Komputer TK6383

Download Report

Transcript Rangkaian Komputer TK6383

TCP socket
application
Architecture
of Client-Server Applications
Java Socket Programming
Client Application
Server Application
norly@ftsm.ukm.my
1
Evolution of Application Architectures
norly@ftsm.ukm.my
2
Java – is one of the earliest programming
language to support 3-tier and n-tier
architecture.
 Java’s strength is in developing enterprise
software (J2EE) as it simplify developer’s
job in implementing the newer application
architecture – from 3-tier to n-tier to mobile.

norly@ftsm.ukm.my
3
3-tier Client-Server Application
norly@ftsm.ukm.my
4
A Bug Tracking System (3-tier)
norly@ftsm.ukm.my
5
Socket-based Client-Server
Application : ALI BABA
norly@ftsm.ukm.my
6
TCP overview


Unlike UDP which is concerned with the
transmission of packets of data, TCP
establishes a "virtual connection" between
two machines through which streams of
data may be sent.
TCP guarantees delivery and order,
providing a reliable byte communication
stream between client and server that
supports two-way communication.
norly@ftsm.ukm.my
7
Establish a virtual connection
Transmit data back and forth
Terminate the connection
norly@ftsm.ukm.my
8



TCP uses IP (Internet Protocol) to establish
the connection between machines.
This connection provides an interface that
allows streams of bytes to be sent and
received, and transparently converts the
data into IP datagram packets.
The virtual connection between two
machines is represented by a socket.
norly@ftsm.ukm.my
9
What is a socket?





Original idea came from UNIX
“The network is just like a file system”
Read and write a stream of data “to the
network” through socket
Stream? ( recall : using package java.io )
A socket is bound to a port number so that the
TCP layer can identify the correct application
for the data
norly@ftsm.ukm.my
10
A little background

Socket provides the TCP/IP communication
protocol



Is supported by all OS




Introduced in 1981- UNIX BSD 4.2
Later Sun build RPC and NFS over the socket
WinSocks for Windows 3.1
Built into Windows 95, … and NT
For other OS – it is not new
Is the De Facto in network communication
norly@ftsm.ukm.my
11
Communication between processes :
using port and socket
socket
any port
agreed port
socket
message
client
server
other ports
Internet address = 138.37.94.248
Internet address = 138.37.88.249
• Port: The destination of a message
• Socket: The final point for processes communication
• Each socket is associated with UDP or TCP
norly@ftsm.ukm.my
12


Like ports in UDP, ports in TCP are also
represented by a number in the range 1 - 65535.
Ports below 1024 are restricted to use by wellknown services. For example,




Telnet (port 23)
SMTP (port 25)
HTTP (port 80)
POP3 (port 110)
norly@ftsm.ukm.my
13
TCP vs UDP

TCP sockets are different from UDP
sockets:



TCP sockets are connected to a single machine.
UDP sockets only send and receive packets of
data.
TCP allows transmission of data through byte
streams. They are converted into datagram
packets for transmission over the network
without programmer intervention.
norly@ftsm.ukm.my
14
Advantages of TCP over UDP

Automatic Error Control


Data transmission is more dependable. Delivery
of data is guaranteed - lost data packets are
retransmitted.
By means of a timer, TCP retransmits a packet if
an acknowledgement is not received from the
recipient within a specified amount of time.
norly@ftsm.ukm.my
15

Reliability

As packets are delivered by IP, they will
frequently arrive out of order. However, each
packet contains a sequence number. Using this
sequence number and queuing out-of-order
packets, TCP is able to pass arriving packets to
the application in the correct sequence.
norly@ftsm.ukm.my
16

Ease of Use

Network programmers will find programming
communication via TCP sockets far simpler than
via datagram packets. This is because data sent
and received can be treated as a continuous
stream (like I/O streams). The data need not be
packaged into discrete units like UDP.
norly@ftsm.ukm.my
17
Socket Operations

TCP sockets can perform a variety of
operations:




Establish a connection to a remote host
Send data to a remote host
Receive data from a remote host
Close a connection
norly@ftsm.ukm.my
18

There is a special type of socket that
provides a service that will bind to a
specific port number. Normally used only in
servers, this socket can perform the
following operations:



Bind to a local port
Accept incoming connections from remote hosts
Unbind from a local port
norly@ftsm.ukm.my
19
TCP and the Client/Server Paradigm



In network programming, applications that
use sockets are divided into clients and
servers.
A client is software that initiates a
connection and sends requests.
A server is software that listens for
connections and processes requests.
norly@ftsm.ukm.my
20


Note that in the context of UDP
programming, no actual connection is
established. UDP applications may both
initiate and receive requests on the same
socket.
In the client/server paradigm, when there is
a connection between two applications, one
must be a client and the other must be a
server.
norly@ftsm.ukm.my
21
Network Clients



Network clients initiate connections and
control network transactions.
The server fulfills the requests of the client
but not the other way round.
The network client speaks to the server
using a network protocol. E.g an HTTP
client communicates with an HTTP server
using HTTP.
norly@ftsm.ukm.my
22

Port numbers are used to enable clients to
locate server applications. E.g. a web
server uses port 80.
norly@ftsm.ukm.my
23
Network Servers



The role of the network server is to bind to a
specific port and to listen for new connections.
Unlike the client, the server must run continually
in the hope that some client will want its services.
The server runs indefinitely. Normally, it is
automatically started when the host computer of
the server is started.
norly@ftsm.ukm.my
24



Some servers can handle only one connection at
a time, while others can handle many connections
concurrently, through the use of threads.
Some protocols (e.g. HTTP/1.0) normally allow
only one request per connection. Others, like
POP3, support a sequence of requests.
Servers answer the client request by sending
either a response or an error message.
norly@ftsm.ukm.my
25
Socket Types

In Java, there are 4 main socket types:





ServerSocket
Socket
DatagramSocket
MulticastSocket
Accessible by importing java.net.*;
norly@ftsm.ukm.my
26
TCP Sockets and Java

Java provide the following classes for TCP
sockets:




java.net.Socket
java.net.ServerSocket
The Socket class should be used when
writing client software.
The ServerSocket class should be used
when writing server software.
norly@ftsm.ukm.my
27
Socket Class

Socket objects represent client sockets,
and is a communication channel between
two TCP communications ports belonging
to one or two machines.
norly@ftsm.ukm.my
28

There are several constructors for the
Socket class.

The easiest way to create a socket is
shown below:
Socket mySocket;
try {
mySocket = new Socket("www.aol.com",
80);
} catch (Exception e) {
…
}
norly@ftsm.ukm.my
29
Socket Constructors

From 8 constructors, 4 are commonly used:

public Socket(InetAddress address, int port)

Throws java.io.IOException, java.lang.SecurityException
Creates a stream socket and connects it to the specified port number at the specified IP
address.
.

public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

Throws java.io.IOException, java.lang.SecurityException
Creates a socket and connects it to the specified remote address on the specified remote
port.

public Socket(String host, int port)

Throws java.io.IOException, java.lang.SecurityException
Creates a stream socket and connects it to the specified port number on the named host.

public Socket(String host, int port, InetAddress localAddr, int localPort)

Throws java.net.UnknownHostException, java.io.IOException,
java.lang.SecurityException
Creates a socket and connects it to the specified remote host on the specified remote
port.
norly@ftsm.ukm.my
30
Reading from and Writing to TCP
Sockets

In Java, once a socket is created, it is
connected and ready to read/write by using
the socket's input and output streams. Use
the methods getInputStream() and
getOutputStream() to access those
streams.
norly@ftsm.ukm.my
31
 Example:
Socket socket;
InputStreamReader isr;
BufferedReader br;
PrintStream ps;
try {
socket = new Socket("www.aol.com",80);
isr = new InputStreamReader(socket.getInputStream());
br = new BufferedReader(isr);
ps = new PrintStream(socket.getOutputStream());
} catch (Exception e) {
…
}
norly@ftsm.ukm.my
32
Methods of class Socket
public InputStream getInputStream();
Returns an input stream for this socket.

public OutputStream getOutputStream();
Returns an output stream for this socket.

Returned stream
depends on TCP flow
control and error
correction.
public void close();
Closes this socket.

public int getPort();
Returns a remote port associated to the socket.

public InetAddress getInetAddress();
Returns an address associated to the socket.

public int getLocalPort();
Returns a local port associated to the socket.

norly@ftsm.ukm.my
33
Server Socket




Server socket is bound to a certain port of a
local host
When it is successfully bound to a port, it
immediately listens to any attempt of incoming
connection
When a server detects an attempt of incoming
connection, it accept the connection
This creates a socket which handles
communication between the client and server
norly@ftsm.ukm.my
34
ServerSocket Class
java.net.ServerSocket represents the
serve socket
 ServerSocket object is created on a local
port and calls method accept() to listen to
incoming connection
 accept() will block until a connection is
detected. Then it returns a Socket object
that handles communication with a client

norly@ftsm.ukm.my
35

The easiest way to create a socket to listen
at a certain port is shown below:
ServerSocket mySocket;
try {
mySocket = new ServerSocket(80);
} catch (Exception e) {
…
}
norly@ftsm.ukm.my
36
ServerSocket Constructors

Some of the other constructors:

ServerSocket(int port)

Throws java.io.IOException,
java.lang.SecurityException
If port is 0, then any free port will be used.

By default, the queue size is set to 50.


ServerSocket(int port, int maxClients)


Throws java.io.IOException,
java.lang.SecurityException
Allocates sufficient space to the queue to support
the specified number of client sockets.
norly@ftsm.ukm.my
37
Methods of class ServerSocket

public Socket accept();


public void close();


Listens for a connection to be made to this socket
and accepts it.
Closes this socket.
public InetAddress getInetAddress();

Returns the local address of this server socket.
norly@ftsm.ukm.my
38




When a ServerSocket object is created, it
attempts to bind to the port on the local host given
by the port argument.
If another server socket is already listening to the
port, then a java.net.BindException, a subclass of
IOException, is thrown.
No more than one process or thread can listen to
a particular port at a time. This includes non-Java
processes or threads.
For example, if there's already an HTTP server
running on port 80, you won't be able to bind to
port 80.
norly@ftsm.ukm.my
39

If you want your process to wait (listening) incoming
connections at a specified port, ServerSocket class
allow it to detect the incoming connection:
ServerSocket outSock = new ServerSocket
(8888);
while (true) {
Socket inSock = outSock.accept();
handleConnection(inSock);
inSock.close();
}
norly@ftsm.ukm.my
40
Accepting and Processing Requests
from TCP Clients


The most important function of a server socket is
to accept client sockets. Once a client socket is
obtained, the server can perform all the "real
work" of server programming, which involves
reading from and writing to the socket to
implement a network protocol.
Example: a mail server that provides access to
stored messages would listen to commands and
send back message contents.
norly@ftsm.ukm.my
41
 Example:
ServerSocket server;
BufferedReader reader;
PrintWriter writer;
server = new ServerSocket(13);
while (true) {
Socket client = server.accept();
reader = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
writer = new PrintWriter(
new OutputStreamWriter(
client.getOutputStream()));
…
}
norly@ftsm.ukm.my
42
ALI BABA Client-Server Apps
norly@ftsm.ukm.my
43
Client Application


The example consists of two applications
which is executed separately
The client app is implemented as
NyietInSengClient class
norly@ftsm.ukm.my
44
import java.io.*;
import java.net.*;
BufferedReader stdIn = new
BufferedReader(new
InputStreamReader(System.in));
String fromServer;
String fromUser;
public class NyietInSengClient {
public static void main(String[] args)
throws IOException {
Socket nisSocket = null;
PrintWriter out = null;
BufferedReader in = null;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " +
fromServer);
if (fromServer.equals("tata titi tutu"))
break;
try {
nisSocket = new Socket("localhost", 8888);
out = new
PrintWriter(nisSocket.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(nisSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host:
localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the
connection to: localhost.");
System.exit(1);
}
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " +
fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
nisSocket.close();
}
}
norly@ftsm.ukm.my
45
Server Application

Server app is implemented using 2 classes:

NyietInSengServer

NyietInSengServer contains the main() method for
the server app. It listens at a port, accepts
connection, read from and write to the socket.
norly@ftsm.ukm.my
46
PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new
InputStreamReader(clientSocket.getInputStream()
));
String inputLine, outputLine;
NyietInSengProtocol nis = new
NyietInSengProtocol();
import java.net.*;
import java.io.*;
public class NyietInSengServer {
public static void main(String[] args) throws
IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on
port: 8888.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
outputLine = nis.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = nis.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("tata titi tutu"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
norly@ftsm.ukm.my
47
Server Application

NyietInSengProtocol


NyietInSengProtocol provides the jokes. It tracks
the current joke, current status (SENTTOKTOK,
SENTCLUE, etc) and returns jokes text based on
the current status.
It implements the communication protocol agreed
by the client and server.
norly@ftsm.ukm.my
48
Server Application
The server app begins by creating a ServerSocket
object to listen (wait) at a specified port. When
selecting a port number use the one not defined for
other services. NyietInSengServer waits at port 8888
because 8/8 is my birthdate (ONG) and port 8888 is not
used in my computer environment
try {
serverSocket = new ServerSocket(8888);
}
catch (IOException e) {
System.out.println("Could not listen on port: 8888");
System.exit(-1);
}

norly@ftsm.ukm.my
49
Server Application


Constructor ServerSocket throws an
exception if it cannot listen to the specified
port (in used).
In this kes NyietInSengServer has no other
choice than to end the program. (exit).
norly@ftsm.ukm.my
50

If server manage to connect to the specified
port, then a ServerSocket object is created and
the next step is executed- accept client
connection (bold):
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 8888");
System.exit(-1);
}
norly@ftsm.ukm.my
51
Server Application




accept() waits until client program is executed
and request for connection to host and port. (In
example: host : localhost and port : 8888.
When connection is successful, method
accept() will return a new Socket object (i.e
:clientSocket) which is bound to a new port.
Server program can communicate with client via
this new socket. It can continue waiting for the
next incoming call through the original
ServerSocket object (in the program :
serverSocket)
Nevertheless in this example, server app cannot
wait for more than 1 client
norly@ftsm.ukm.my
52
Read/Write
1.
Gets the socket's input and output stream
and opens readers and writers on them
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader( new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
norly@ftsm.ukm.my
53
2.
After the server successfully establishes a
connection with a client, it communicates
with the client using this code:

// initiate conversation with client
NyietInSengProtocol nis = new NyietInSengProtocol();
outputLine = nis.processInput(null);
out.println(outputLine);
norly@ftsm.ukm.my
54
while ((inputLine = in.readLine()) != null) {
outputLine = nis.processInput(inputLine);
out.println(outputLine);
if outputLine.equals(“tata titi tutu"))
break;
}
3. Communicates with the client by reading
from and writing to the socket (the while
loop).
norly@ftsm.ukm.my
55



1 is already familiar. Step 2 is shown in bold and
is worth a few comments.
After the NyietInSengProtocol is created, the
code calls NyietInSengProtocol 's processInput
method to get the first message that the server
sends to the client.
For this example, the first thing that the server
says is “NyietInSeng MatekAji Semar Ngiseng!"
Next, the server writes the information to the
PrintWriter connected to the client socket,
thereby sending the message to the client.
norly@ftsm.ukm.my
56
AliBaba Communication Protocol

Following is the class implementation of the
protocol
norly@ftsm.ukm.my
57
import java.net.*;
import java.io.*;
public class NyietInSengProtocol {
private static final int WAITING = 0;
private static final int SENTTOKTOK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;
private static final int NUMJOKES = 3;
private int state = WAITING;
private int currentJoke = 0;
private String[] clues =
{ "Ali", "Di Sini", "Hari"};
private String[] answers =
{ "Ali Baba, Bujang Lapok la.. ",
"Di Sini lah, Oi Di Sana! ",
"Harimau Kuat! Grrrrrr "};
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "NyietInSeng MatekAji Semar Ngiseng!";
state = SENTTOKTOK;
} else if (state == SENTTOKTOK) {
if (theInput.equalsIgnoreCase("Siapa tu?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "Sepatutnya awak cakap \"Siapa tu?\"! " +
"Cuba lagi. NyietInSeng MatekAji Semar
Ngiseng!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " mana?")) {
theOutput = answers[currentJoke] + " Main lagi? (y/n)";
state = ANOTHER;
} else {
theOutput = "Sepatutnya awak cakap \"" +
clues[currentJoke] +
" mana?\"" +
"! Cuba lagi. NyietInSeng MatekAji Semar
Ngiseng!";
state = SENTTOKTOK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "NyietInSeng MatekAji Semar Ngiseng!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTTOKTOK;
} else {
theOutput = "tata titi tutu";
state = WAITING;
}
}
return theOutput;
}
}
norly@ftsm.ukm.my
58