Lecture 10: Networking using Socket Programming. Client-Server Model b The term server applies to any program that offers a service that can be reached.

Slides:



Advertisements
Similar presentations
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Advertisements

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.
COMP201 Java Programming Part III: Advanced Features Topic 14: Networking Volume II,Chapter 3.
COMP201 Java Programming Part III: Advanced Features Topic 13: Networking Volume II,Chapter 3.
Socket Programming.
1 Java Networking – Part I CS , Spring 2008/9.
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 Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.
COMP1681 / SE15 Introduction to Programming
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Java Networking – part I CS , Winter 2007/8.
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
Process-to-Process Delivery:
EE2E1. JAVA Programming Lecture 9 Network Programming.
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
SOCKET PROGRAMMING. Client/Server Communication At a basic level, network-based systems consist of a server, client, and a media for communication as.
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.
Import java.net.*; import java.io.*; public class LowPortScanner { public static void main(String[] args) { String host = "localhost"; if (args.length.
DBI Representation and Management of Data on the Internet.
 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.
1. I NTRODUCTION TO N ETWORKS Network programming is surprisingly easy in Java ◦ Most of the classes relevant to network programming are in the java.net.
Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.
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.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Introduction to Sockets “A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
StreamTokenizer Break up a stream of text into pieces called tokens A token is the smallest unit recognized by a text parsing algorithm (words, symbols,
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,
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Computer Networks & PROTOCOLS (CSI 4118) FALL 2005 Professor Robert L. Probert.
Socket Programming Introduction. Socket Definition A network socket is one endpoint in a two-way communication flow between two programs running over.
Java Server Programming Web Interface for Java Programs.
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.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
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.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
第十一讲 分布式编程 Socket and RMI 李庆旭. 2 本章内容提要  Socket TCP /IP protocol suit Socket A TCP Server and a TCP Client Supporting Multiple Concurrent Clients A UDP.
Java Networking I IS Outline  Quiz #3  Network architecture  Protocols  Sockets  Server Sockets  Multi-threaded Servers.
Network Programming James Atlas July 10, James Atlas - CISC3702 Review Multi-Threaded Programming Multi-Threaded Programming  Processes  Threads.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
SOCKET PROGRAMMING WITH JAVA By Collin Donaldson.
1 Network Communications A Brief Introduction. 2 Network Communications.
Advance Computer Programming Networking Basics – explores the java.net package which provides support for networking. – Also Called “programming for the.
Working with URLs CSIE, National University of Tainan.
Network Programming. These days almost all devices.
MCA – 405 Elective –I (A) Java Programming & Technology
Networking with Java 2.
Lecture 9 Network Programming
„Networking”.
Socket programming - Java
Distributed Computing
Multiplexing/Demux.
CS18000: Problem Solving and Object-Oriented Programming
Presentation transcript:

Lecture 10: Networking using Socket Programming

Client-Server Model b The term server applies to any program that offers a service that can be reached over a network. A server accepts a request over the network, performs its service, and returns the result to the requester. b An executing program becomes a client when it sends a request to a server and waits for a response.

Socket Interface b Sockets provide low level communication mechanism that allow two processes to communicate on same machine or on different machine. b Funded by ARPA (Advanced Research Projects Agency) in b Developed at UC Berkeley. b Objective is to transport TCP/IP software to UNIX b Now Socket interface has become de facto standard.

Socket b Socket is a generalization of the UNIX file access mechanism that provides an endpoint for communication. b Program request the Operating system to create a socket when one is needed. b The system will return a small integer value that the program uses to reference the newly created socket. b The application can choose to supply a destination address each time it uses the socket (e.g., when sending datagrams), or it can choose to bind the destination address to the socket and avoid specifying the destination repeatedly (e.g., when making a TCP connection).

Socket Primitives (General approach) b SOCKET Create a new communication end point b BIND Attach a local address to a socket b LISTEN Announce willingness to accept connections. b ACCEPT Block the caller until a connection attempt arrives b CONNECT Actively attempt to establish a connection b SEND Send some data over the connection b RECEIVE Receive some data from the connection b CLOSE Release the connection

Passive/Active Socket b A passive socket is used by a server to wait for an incoming connection. b An active socket is used by a client to initiate a connection.

SocketTest.java import java.io.*; import java.net.*; public class SocketTest { public static void main(String[] args) public static void main(String[] args) { try try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 13);

SocketTest.java (Cont.) BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); (new InputStreamReader(s.getInputStream())); boolean more = true; boolean more = true; while (more) while (more) { String line = in.readLine(); if (line == null) more = false; if (line == null) more = false; else else System.out.println(line); System.out.println(line); } }

Cont. catch (IOException e) { System.out.println("Error" + e); } }}

Example import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL(" + "tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); } }

Output protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING

Socket timeouts b We can set timeout value for a socket object. If we don’t set it then we are on the mercy of underlying operating system. E.g., if we call a read method on a Socket object, it will block our socket until read method will return.

SocketOpenerTest.java import java.io.*; import java.net.*; public class SocketOpenerTest { public static void main(String[] args) { String host; String host; if (args.length > 0) host = args[0]; if (args.length > 0) host = args[0]; else host = " else host = " int port; int port;

SocketOpenerTest.java Cont. if (args.length > 1) port = Integer.parseInt(args[1]); else port = 80; else port = 80; int timeout = 5000; Socket s = SocketOpener.openSocket(host, port, timeout); Socket s = SocketOpener.openSocket(host, port, timeout); if (s == null) System.out.println("The socket could not be opened."); System.out.println("The socket could not be opened."); else else System.out.println(s); System.out.println(s); }}

SocketOpenerTest.java Cont. class SocketOpener implements Runnable { public static Socket openSocket(String aHost, int aPort, int timeout) int timeout) { SocketOpener opener = new SocketOpener(aHost, aPort); { SocketOpener opener = new SocketOpener(aHost, aPort); Thread t = new Thread(opener); Thread t = new Thread(opener); t.start(); t.start(); try try { t.join(timeout); { t.join(timeout); }

SocketOpenerTest.java Cont. catch (InterruptedException exception) { } return opener.getSocket(); return opener.getSocket(); } public SocketOpener(String aHost, int aPort) { socket = null; { socket = null; host = aHost; host = aHost; port = aPort; }

SocketOpenerTest.java Cont. public void run(){ try{ try{ socket = new Socket(host, port); } catch (IOException exception){ catch (IOException exception){ } } public Socket getSocket(){ return socket; } private String host; private String host; private int port; private int port; private Socket socket; private Socket socket;};

Internet addresses b High level names are mapped with IP addresses. b You can use InetAddress class if you need to convert between host names and internet addresses. InetAddress address = InetAddress.getByName(“time- A.timefreq.bldrdoc.gov”) ; This method will return b The address is reserved for a local machine and usually used for testing.

InetAddressTest.java import java.net.*; public class InetAddressTest { public static void main(String[] args) { try try { if (args.length > 0) if (args.length > 0) { String host = args[0]; { String host = args[0]; InetAddress[] addresses InetAddress[] addresses = InetAddress.getAllByName(host); = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) for (int i = 0; i < addresses.length; i++) System.out.println(addresses[i]); System.out.println(addresses[i]); }

Cont. else { InetAddress localHostAddress { InetAddress localHostAddress = InetAddress.getLocalHost(); = InetAddress.getLocalHost(); System.out.println(localHostAddress); System.out.println(localHostAddress); } } catch (Exception e) catch (Exception e) { System.out.println("Error: " + e); { System.out.println("Error: " + e); } }}

TCP/IP b Transmission Control Protocol standard transport level protocol that provides the reliable, full duplex, stream service on which many application protocols depend. TCP allows a process on one machine to send a stream of data to a process on another. TCP is connection-oriented in the sense that before transmitting data, participants must establish a connection. All data travels in TCP segments, which each travel across the Internet in an Ip datagram. The entire protocol suite is often referred to as TCP/IP because TCP and IP are the two fundamental protocols.

The User Datagram Protocol (UDP) b The User Datagram Protocol (UDP) provides an unfeliable conncetionless delivery service using IP to transport messages between machines. It uses IP to carry messages, but adds the ability to distinguish among multiple destinations within a fiven host computer.

Layers of Communication Conceptual View

Usage of Ports Definition: The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure: Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 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.

Inter Process Communication Usage of Ports in Processes communication

ServicePort Number ServicePort Number b FTP21 b Telnet23 b SMTP Mail 25 b HTTP (Web) 80 b POP3 Mail 110 b News119

Implementing Servers b Server program binds himself on a specific port no. and listen for the client request. Then it sends information on the Net that was requested by client. Following will establish a server that monitors port ServerSocket s = new ServerSocket (8189) ; Following will tells the program to wait indefinitely until a client connects to that port. After connection it will return a socket object that can be used for I/O. BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */);

Implementing Servers Cont. b Every thing that server sends to the server output stream becomes the input of the client program and all the output from the client program ends up in the server input stream.

EchoServer.java import java.io.*; import java.net.*; public class EchoServer{ public static void main(String[] args ) {try { ServerSocket s = new ServerSocket(8189); ServerSocket s = new ServerSocket(8189); Socket incoming = s.accept( ); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); (new InputStreamReader(incoming.getInputStream()));

EchoServer.java Cont PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) while (!done) { String line = in.readLine(); { String line = in.readLine(); if (line == null) done = true; if (line == null) done = true; else else { out.println("Echo: " + line); { out.println("Echo: " + line);

EchoServer.java Cont if (line.trim().equals("BYE")) done = true; done = true; } } incoming.close(); incoming.close(); } catch (Exception e) catch (Exception e) {System.out.println(e); } }}

ThreadedEchoServer.java import java.io.*; import java.net.*; public class ThreadedEchoServer { public static void main(String[] args ) { int i = 1; { int i = 1; try try { ServerSocket s = new ServerSocket(8189); { ServerSocket s = new ServerSocket(8189); for (;;) for (;;) { Socket incoming = s.accept( ); { Socket incoming = s.accept( ); System.out.println("Spawning " + i); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); new ThreadedEchoHandler(incoming, i).start(); i++; i++; } }

ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); { System.out.println(e); } }} class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; }

ThreadedEchoServer.java Cont public void run() {try { BufferedReader in = new BufferedReader BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); out.println( "Hello! Enter BYE to exit." ); boolean done = false; boolean done = false;

ThreadedEchoServer.java Cont while (!done) { String str = in.readLine(); { String str = in.readLine(); if (str == null) done = true; if (str == null) done = true; else else { out.println("Echo (" + counter + "): " + str); { out.println("Echo (" + counter + "): " + str); if (str.trim().equals("BYE")) done = true; done = true; } } incoming.close(); incoming.close(); }

ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); { System.out.println(e); } } private Socket incoming; private Socket incoming; private int counter; private int counter;}

URLConnectionReader.java import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { URL yahoo = new URL(" URL yahoo = new URL(" URLConnection yc = yahoo.openConnection(); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( BufferedReader in = new BufferedReader( new InputStreamReader( new InputStreamReader( yc.getInputStream())); yc.getInputStream())); String inputLine; String inputLine; while ((inputLine = in.readLine()) != null) while ((inputLine = in.readLine()) != null) System.out.println(inputLine); System.out.println(inputLine); in.close(); in.close(); }}

Reverse.java import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse " System.err.println("Usage: java Reverse " + "string_to_reverse"); + "string_to_reverse"); System.exit(1); System.exit(1);} String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL(" URLConnection connection = url.openConnection(); connection.setDoOutput(true);

Reverse.java Cont. PrintWriter out = new PrintWriter( connection.getOutputStream()); connection.getOutputStream()); out.println("string=" + stringToReverse); out.close(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); System.out.println(inputLine);in.close(); }}

An Example of Client-Server application

ThreadedDataObjectServer.java import java.io.*; import java.net.*; import java.net.*; public class ThreadedDataObjectServer { public static void main(String[] args ) { try{ ServerSocket s = new ServerSocket(3000); for (;;) { Socket incoming = s.accept( ); new ThreadedDataObjectHandler(incoming).start(); }}

Server Cont. catch (Exception e) {System.out.println(e);}}} class ThreadedDataObjectHandler extends Thread { public ThreadedDataObjectHandler(Socket i) { incoming = i; }

Server Cont. public void run() { try{ ObjectInputStream in = new ObjectInputStream(incoming.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(incoming.getOutputStream()); myObject = (DataObject)in.readObject(); ObjectInputStream in = new ObjectInputStream(incoming.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(incoming.getOutputStream()); myObject = (DataObject)in.readObject(); System.out.println("Message read: " + myObject.getMessage());

Server Cont. myObject.setMessage("Got it!"); System.out.println("Message written: " + myObject.getMessage()); out.writeObject(myObject);in.close(); out.close(); out.close();incoming.close();}

Server Cont. catch (Exception e) { System.out.println(e); System.out.println(e);}} DataObject myObject = null; private Socket incoming; private Socket incoming;}

DataObject.java import java.io.*; import java.util.*; public class DataObject implements Serializable{ private int number; DataObject(){ number = 2; } public int getNumber(){ return number; } public void setNumber(int inNumber){ number = inNumber; }}

Client.java mport java.io.*; import java.net.*; import java.net.*; public class Client{ public static void main(String[] arg){ try{ DataObject myObject = new DataObject(); myObject.setNumber(1); System.out.println("Number : " + myObject.getNumber()); Socket socketToServer = new Socket(" ", 3000); ObjectOutputStream myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream()) ; System.out.println("Number : " + myObject.getNumber()); Socket socketToServer = new Socket(" ", 3000); ObjectOutputStream myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream()) ;

Client ObjectInputStream myInputStream = new ObjectInputStream(socketToServer.getInputStream()); myOutputStream.writeObject(myObject); myObject = (DataObject)myInputStream.readObject(); System.out.println("Number : " + myObject.getNumber()); myOutputStream.close(); myInputStream.close(); myInputStream.close();socketToServer.close(); } catch(Exception e){ System.out.println(e); }}}

The End of Lecture 10