[email protected] 1 TCP socket application Architecture of Client-Server Applications Java Socket...

58
[email protected] 1 TCP socket application Architecture of Client-Server Applications Java Socket Programming Client Application Server Application
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    225
  • download

    3

Transcript of [email protected] 1 TCP socket application Architecture of Client-Server Applications Java Socket...

[email protected] 1

TCP socket application

Architecture of Client-Server ApplicationsJava Socket ProgrammingClient ApplicationServer Application

[email protected]

2

Evolution of Application Architectures

[email protected]

3

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.

[email protected]

4

3-tier Client-Server Application

[email protected]

5

A Bug Tracking System (3-tier)

[email protected]

6

Socket-based Client-Server Application : ALI BABA

[email protected]

7

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.

[email protected]

8

Establish a virtual connection

Terminate the connection

Transmit data back and forth

[email protected]

9

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.

[email protected]

10

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

[email protected]

11

A little background Socket provides the TCP/IP communication

protocol Introduced in 1981- UNIX BSD 4.2 Later Sun build RPC and NFS over the socket

Is supported by all OS 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

[email protected]

12

Communication between processes : using port and socket

message

agreed portany port

socketsocket

Internet address = 138.37.88.249Internet address = 138.37.94.248

other ports

client server

• Port: The destination of a message• Socket: The final point for processes communication• Each socket is associated with UDP or TCP

[email protected]

13

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 well-known services. For example, Telnet (port 23) SMTP (port 25) HTTP (port 80) POP3 (port 110)

[email protected]

14

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.

[email protected]

15

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.

[email protected]

16

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.

[email protected]

17

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.

[email protected]

18

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

[email protected]

19

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

[email protected]

20

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.

[email protected]

21

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.

[email protected]

22

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.

[email protected]

23

Port numbers are used to enable clients to locate server applications. E.g. a web server uses port 80.

[email protected]

24

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.

[email protected]

25

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.

[email protected]

26

Socket Types In Java, there are 4 main socket types:

ServerSocket Socket DatagramSocket MulticastSocket

Accessible by importing java.net.*;

[email protected]

27

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.

[email protected]

28

Socket Class

Socket objects represent client sockets, and is a communication channel between two TCP communications ports belonging to one or two machines.

[email protected]

29

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) {

}

[email protected]

30

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.

[email protected]

31

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.

[email protected]

32

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) {…

}

[email protected]

33

public InputStream getInputStream(); Returns an input stream for this socket.

public OutputStream getOutputStream(); Returns an output stream for this socket.

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.

Returned stream depends on TCP flow control and error

correction.

Methods of class Socket

[email protected]

34

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

[email protected]

35

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

[email protected]

36

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) {

}

[email protected]

37

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.

[email protected]

38

Methods of class ServerSocket public Socket accept();

Listens for a connection to be made to this socket and accepts it.

public void close(); Closes this socket.

public InetAddress getInetAddress(); Returns the local address of this server socket.

[email protected]

39

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.

[email protected]

40

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(); }

[email protected]

41

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.

[email protected]

42

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()));

…}

[email protected]

43

ALI BABA Client-Server Apps

[email protected]

44

Client Application The example consists of two applications

which is executed separately The client app is implemented as

NyietInSengClient class

[email protected]

45

import java.io.*;import java.net.*;

public class NyietInSengClient { public static void main(String[] args) throws IOException { Socket nisSocket = null; PrintWriter out = null; BufferedReader in = null;

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); }

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

String fromServer; String fromUser;

while ((fromServer = in.readLine()) != null) { System.out.println("Server: " +

fromServer); if (fromServer.equals("tata titi tutu")) break;

fromUser = stdIn.readLine();

if (fromUser != null) { System.out.println("Client: " +

fromUser); out.println(fromUser);

} }

out.close(); in.close(); stdIn.close(); nisSocket.close(); }}

[email protected]

46

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.

[email protected]

47

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); }

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader in = new BufferedReader(new

InputStreamReader(clientSocket.getInputStream()));

String inputLine, outputLine; NyietInSengProtocol nis = new

NyietInSengProtocol();

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(); }}

[email protected]

48

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.

Server Application

[email protected]

49

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); }

Server Application

[email protected]

50

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).

Server Application

[email protected]

51

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);

}

[email protected]

52

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

Server Application

[email protected]

53

Read/Write1. Gets the socket's input and output stream

and opens readers and writers on themPrintWriter out = new PrintWriter(clientSocket.getOutputStream(),

true);

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

String inputLine, outputLine;

[email protected]

54

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);

[email protected]

55

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).

[email protected]

56

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.

[email protected]

57

AliBaba Communication Protocol Following is the class implementation of the

protocol

[email protected]

58

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; }}