1 TCP socket application Architecture of Client-Server Applications Java Socket Programming Client Application Server Application.

Slides:



Advertisements
Similar presentations
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Advertisements

Network Programming Chapter 11 Lecture 6. Networks.
Prepared By E. Musa Alyaman1 Java Network Programming TCP.
Socket Programming.
1 Java Networking – Part I CS , Spring 2008/9.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
System Programming Practical session 10 Java sockets.
Java sockets. From waiting.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Socket-based Client- Server Application Client-Server application architecture Choosing services – Connectionless atau Connection-oriented.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
DBI Representation and Management of Data on the Internet.
1 CSCD 330 Network Programming Winter 2015 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 6 Application.
 TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.  TCP/IP Stack Application.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Java Socket programming. Socket programming with TCP.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
VII. Sockets. 1. What is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes.
CSC 480 Software Engineering Socket. What is Socket? A socket is one end-point of a two-way communication link between two programs running on the network.
Part 4: Network Applications Client-server interaction, example applications.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 CSCD 330 Network Programming Winter 2016 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 6 Application.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
1 Socket-based Client- Server Application Client-Server application architecture Choosing services – Connectionless atau Connection-oriented.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
1 Network Communications A Brief Introduction. 2 Network Communications.
Network Programming. These days almost all devices.
Object-Orientated Analysis, Design and Programming
Lecture 21 Sockets 1 (Not in D&D) Date.
Socket-based Client-Server Application
MCA – 405 Elective –I (A) Java Programming & Technology
Networking with Java 2.
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
„Networking”.
CSCD 330 Network Programming
Socket programming - Java
Socket-based Client-Server Application
Exceptions and networking
Presentation transcript:

1 TCP socket application Architecture of Client-Server Applications Java Socket Programming Client Application Server Application

2 Evolution of Application Architectures

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.

4 3-tier Client-Server Application

5 A Bug Tracking System (3-tier)

6 Socket-based Client-Server Application : ALI BABA

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.

8 Establish a virtual connection Terminate the connection Transmit data back and forth

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.

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

11 A little background Socket provides the TCP/IP communication protocol Introduced in 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

12 Communication between processes : using port and socket message agreed port any port socket Internet address = Internet address = 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

13 Like ports in UDP, ports in TCP are also represented by a number in the range 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)

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.

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.

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.

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.

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

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

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.

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.

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.

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

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.

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.

26 Socket Types In Java, there are 4 main socket types: ServerSocket Socket DatagramSocket MulticastSocket Accessible by importing java.net.*;

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.

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

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(" 80); } catch (Exception e) { … }

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.

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.

32 Example: Socket socket; InputStreamReader isr; BufferedReader br; PrintStream ps; try { socket = new Socket(" isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); ps = new PrintStream(socket.getOutputStream()); } catch (Exception e) { … }

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

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

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

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

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.

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.

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.

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

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.

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

43 ALI BABA Client-Server Apps

44 Client Application The example consists of two applications which is executed separately The client app is implemented as NyietInSengClient class

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

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.

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

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

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

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

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

52 accept() waits until client program is executed and request for connection to host and port. (In example: host : localhost and port : 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

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

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

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

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.

57 AliBaba Communication Protocol Following is the class implementation of the protocol

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