Java Programming II Java Network (I) Java Programming II.

Slides:



Advertisements
Similar presentations
SOCKET PROGRAMMING WITH MOBILE SOCKET CLIENT DEARTMENT OF COMPUTER SCIENCE IOWA STATE UNIVERSITY.
Advertisements

Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Referring to Java API Specifications
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.
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Socket Programming.
User Datagram Protocol. Introduction UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive.
Prepared By E. Musa Alyaman1 User Datagram Protocol (UDP) Chapter 5.
1 Java Networking – Part I CS , Spring 2008/9.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Lecture 11 Java Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger and Joonbok Lee.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 Inter-Process Communication: Network Programming using TCP Java Sockets Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
Greg Jernegan Brandon Simmons. The Beginning…  The problem Huge demand for internet enabled applications and programs that communicate over a network.
Babak Esfandiari (based on slides by Qusay Mahmoud)
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Socket programming 1. getByName import java.net.*; public class GetHostName { public static void main (String args[]) { String host = "
SOCKET PROGRAMMING. Client/Server Communication At a basic level, network-based systems consist of a server, client, and a media for communication as.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
VIII. UDP Datagrams and Sockets. The User Datagram Protocol (UDP) is an alternative protocol for sending data over IP that is very quick, but not reliable:
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.
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
1 A TCP/IP Application Programming Perspective Chris Greenhalgh G53ACC.
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.
Java Sockets Programming
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.
What is a Network? Computer network Computer network a set of computers using common protocols to communicate over connecting transmission media. a set.
NETWORK PROGRAMMING.
Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.
Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Networking Terminology: ISP (Internet service provider) – dialup, dsl, cable LAN (local area network) IP (internet protocol) address, eg
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.
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.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
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.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Network Programming. These days almost all devices.
Network Programming Communication between processes Many approaches:
Java 13. Networking public class SumTest {
Object-Orientated Analysis, Design and Programming
Secure Sockets SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link between a server and a client—typically.
Network Programming Introduction
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Network Programming Introduction
„Networking”.
CSCD 330 Network Programming
UNIT-6.
Networking.
CSCD 330 Network Programming
Outline Introduction Networking Basics Understanding Ports and Sockets
CSCD 330 Network Programming
Java Socket Programming
Socket Programming with UDP
Review Communication via paired sockets, one local and one remote
Presentation transcript:

Java Programming II Java Network (I) Java Programming II

Contents Internet Addresses Server Sockets and Sockets Datagram Sockets and Packets Uniform Resource Locators (URL) Java Programming II

One or more nodes within the network OSI 7 Layers End host End host Application Application Presentation Presentation Session Session One or more nodes within the network Transport Transport Network Network Network Network Physical Layer: Transmission of Bits Data Link Layer: Convert bits to frame. Error correction Network Layer: Routing between nodes in the packet switching network, Data unit is the packets. Transport Layer: Executes channel between processes. Data unit: message Session Layer: Name space for application characteristics Presentation Layer: Data formation, Encryption Application Layer: Protocol for Application interoperability. Ex) FTP Data Link Data Link Data Link Data Link Physical Physical Physical Physical Java Programming II

Internet Structure FTP HTTP NV TFTP TCP UDP Application IP TCP UDP IP Network Protocol: Network adaptor(hardware), Software (Network device driver), Ex) FDDI IP(Internet Protocol): Supports multi-networking technique as unique logical internetwork TCP/UDP: Provides selective logical channel to application programs. It can be considered as transport protocol of OSI, but usually end-to-end protocol. Network NET1 NET2 NETn Other Structure of Internet Internet Protocol Graph Java Programming II

Internet Addresses GetByName() Method getAllByName() Method Transmission Control Protocol (TCP) : To obtain reliable, sequenced data exchange. User Datagram Protocol (UDP) : To obtain a more efficient, best-effort delivery. import java.net.*; class InetAddressDemo { public static void main(String args[]) { try { InetAddress ias[] = InetAddress.getAllByName(args[0]); for (int i = 0; i < ias.length; i++) { System.out.println(ias[i].getHostName()); System.out.println(ias[i].getHostAddress()); byte bytes[] = ias[i].getAddress(); for (int j = 0; j < bytes.length; j++) { if (j > 0) System.out.print("."); if (bytes[j] >= 0) System.out.print(bytes[j]); else System.out.print(bytes[j] + 256); } System.out.println(""); catch (Exception e) { e.printStackTrace(); GetByName() Method static InetAddress getByName (String hostName) throws UnknownHostException - Determines the IP address of a host, given the host's name. getAllByName() Method static InetAddress[] getAllByName (String hostName) throws UnknownHostException - Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system. getAddress() Method Byte[] InetAddress getLocalHost() - Returns the raw IP address of this InetAddress object. http://java.sun.com/javase/ja/8/docs/ja/api/java/net/InetAddress.html Java Programming II

Socket Call for Connection-Oriented Protocol Server socket() bind() Client listen() socket() accept() connection establishment Blocks until connection from client connect() Data (request) read() write() Process request Data (reply) read() write() Java Programming II

Socket Call for Connectionless Protocol Server socket() Client bind() socket() recvfrom() Blocks until data recv. from client bind() Data (request) sendto() Process request Data (reply) recvfrom() write() Java Programming II

Server Sockets and Sockets Socket Class ServerSocket Constructor This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines. This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester. Socket(String hostName, int port) throws UnknownHostException, IOException - Creates a stream socket and connects it to the specified port number at the specified IP address. ServerSocket(int port) throws IOException - Creates a server socket, bound to the specified port. accept() Method getInputStream(), getOutputStream Method Socket accept() throws IOException - Listens for a connection to be made to this socket and accepts it. InputStream getInputStream() throws IOException Returns an input stream for this socket. OutputStream getOutputStream() throws IOException - Returns an output stream for this socket. bind() Method Socket accept() throws IOException - Binds the ServerSocket to a specific address (IP address and port number). close() close() Method void close() throws IOException - Closes this socket. void close() throws IOException - Closes this socket. http://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html Java Programming II

Server Sockets and Sockets import java.io.*; import java.net.*; import java.util.*; class ServerSocketDemo { public static void main(String args[]) { try { // Get Port int port = Integer.parseInt(args[0]); Random random = new Random(); //Create Server Socket ServerSocket ss = new ServerSocket(port); //Create Infinite Loop while(true) { //Accept Incoming Requests Socket s = ss.accept(); //Write Result to Client OutputStream os = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeInt(random.nextInt()); //Close socket s.close(); } catch (Exception e) { System.out.println("Exception: " + e); } class SocketDemo { public static void main(String args[]) { try { //Get Server and Port String server = args[0]; int port = Integer.parseInt(args[1]); //Create socket Socket s = new Socket(server, port); //Read random number from server InputStream is = s.getInputStream(); DataInputStream dis = new DataInputStream(is); int i = dis.readInt(); //Display Result System.out.println(i); //Close Socket s.close(); } catch (Exception e) { System.out.println("Exception: " + e); } Running : % java ServerSocketDemo 4321 % java SocketDemo 127.0.0.1 4321 Java Programming II

Datagram Sockets and Packets UDP does not guarantee reliable, sequenced data exchange, and therefore requires much less overhead. DatagramPacket Constructor send() Method DatagramPacket(byte buffer[], int size) DatagramPacket(byte buffer[], int size, InetAddress ia, int port) void send(DatagramPacket dp) throws IOException close() Method DatagramSocket() Method void close() DatagramSocket() throws SocketException DatagramSocket(int port) throws SocketException receive() Method void receive(DatagramPacket dp) throws IOException http://docs.oracle.com/javase/8/docs/api/java/net/DatagramPacket.html Java Programming II

Datagram Sockets and Packets class DatagramReceiver { private final static int BUFSIZE = 20; public static void main(String args[]) { try { //Obtain port int port = Integer.parseInt(args[0]); //Create a DatagramSocket object for the port DatagramSocket ds = new DatagramSocket(port); //Create a buffer to hold incoming data byte buffer[] = new byte[BUFSIZE]; //Create infinite loop while(true) { //Create a datagram packet DatagramPacket dp = new DatagramPacket(buffer, buffer.length); //Receive data ds.receive(dp); //Get data from the datagram packet String str = new String(dp.getData()); // Display the data System.out.println(str); } catch (Exception e) { e.printStackTrace(); class DatagramSender { public static void main(String args[]) { try { // Create destination Internet address InetAddress ia = InetAddress.getByName(args[0]); // Obtain destination port int port = Integer.parseInt(args[1]); // Create a datagram socket DatagramSocket ds = new DatagramSocket(); //Create a datagram packet byte buffer[] = args[2].getBytes(); DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, port); // Send the datagram packet ds.send(dp); } catch (Exception e) { e.printStackTrace(); Running : % java DatagramReceiver 4321 % java DatagramSender localhost 4321 Message Java Programming II

Uniform Resource Locators (URL) openStream() Method URL InputStream() throws IOException Protocol://host:/port/file getFile(), getHost(), getPort(), and getProtocol() Methods URL Constructor URL(String protocol, String host, int port, String file) throws MalformedURLException URL(String protocol, String host, String file) throws MalformedURLException URL(String urlString) throws MalformedURLException String getFile() String getHost() int getPort() String getProtocol() Refer to http://docs.oracle.com/javase/8/docs/api/java/net/URL.html Java Programming II

URL Demo Example Run : Java Programming II class URLDemo { public static void main(String args[]) { try { // Obtain URL URL url = new URL(args[0]); // Obtain input stream InputStream is = url.openStream(); // Read and display data from URL byte buffer[] = new byte[1024]; int i; while((i = is.read(buffer)) != -1) { System.out.write(buffer, 0, i); } catch (Exception e) { e.printStackTrace(); Run : java URLDemo http://www.u-aizu.ac.jp Java Programming II

Client and Server Application public void readSocket(){ try { message = dataStream.readUTF(); System.out.println(message + "\n"); if(message.equals("Exit")){ System.exit(0); } catch( UnknownHostException e) { System.out.println("Error : Cannot find server." + e); catch( IOException e ) { System.out.println("Error : I/O Error." + e); public void writeSocket(){ String initmsg_r = new String("Enter your message: "); dataoutputStream.writeUTF(initmsg_r); System.out.print("Enter please for ready... "); message = charStream.readLine(); if (! Message.equals(“Exit”)) return; else {dataoutputStream.writeUTF(“Exit”); System.exit(0); } import java.io.*; import java.net.*; public class Server { public ServerSocket svrSocket = null; public Socket socket = null; public InputStream inputStream = null; public OutputStream outputStream = null; public DataInputStream dataStream = null; public PrintStream printStream = null; public DataOutputStream dataoutputStream = null; public String message; public BufferedReader charStream = new BufferedReader(new InputStreamReader(System.in)); public Server() { try { svrSocket = new ServerSocket(1056); System.out.println("\nInitializint Port..."); System.out.println("\nListen..."); socket = svrSocket.accept(); System.out.println("\nConnect to Client!\n"); inputStream = socket.getInputStream(); dataStream = new DataInputStream(inputStream); outputStream = socket.getOutputStream(); dataoutputStream = new DataOutputStream(outputStream); message = dataStream.readUTF(); System.out.println(message + "\n"); } catch( UnknownHostException e) { System.out.println("Error : Cannot find server." + e); } catch( IOException e ) { System.out.println("Error : I/O Error." + e); Java Programming II

Client and Server Application public static void main(String args[]) { Server svr = new Server(); for(;;){ svr.writeSocket(); svr.readSocket(); } // End of Server dataStream = new DataInputStream(inputStream); outputStream = socket.getOutputStream(); dataoutputStream = new DataOutputStream(outputStream); dataoutputStream.writeUTF(message); } catch(UnknownHostException e) { System.out.println("Error : Cannot find server." + e); } catch(IOException e) { System.out.println("Error : I/O Error." + e); while(true) { try { inputStream = socket.getInputStream(); message = dataStream.readUTF(); System.out.print(message); if(message.equals("Exit")){ System.exit(0); } message = charStream.readLine(); } // end of while } // end of main method } // end of Client Constructor import java.net.*; import java.io.*; public class Client { public static void main(String args[]) { // Initialize the stream OutputStream outputStream = null; DataOutputStream dataoutputStream = null; InputStream inputStream = null; DataInputStream dataStream = null; BufferedReader charStream = null; // Initialize Socket Socket socket = null; String message; try { charStream = new BufferedReader(new InputStreamReader(System.in)); message = new String("Hi! I am a client"); socket = new Socket("127.0.0.1", 1056); Java Programming II