Java Programming The Language of Now & the Future Clients and Servers including Internet connectivity, I/O and JDBC John Morris and Peter Jones Department.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
SOCKET PROGRAMMING WITH MOBILE SOCKET CLIENT DEARTMENT OF COMPUTER SCIENCE IOWA STATE UNIVERSITY.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
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.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Network Programming Chapter 11 Lecture 6. Networks.
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 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
1 Programming Section 9 James King 12 August 2003.
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) 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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
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.
Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Object Persistence and Object serialization CSNB534 Asma Shakil.
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.
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.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
14 - Client/ServerCSC4071 Systems Architecture Client-Server Systems.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed box. I/O gives your Java program access to your hard.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
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.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CSE 501N Fall ‘09 22: Introduction to Networking November Nick Leidenfrost.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Network Programming. These days almost all devices.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Network Programming Communication between processes Many approaches:
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Socket Programming Ameera Almasoud
Beyond HTTP Up to this point we have been dealing with software tools that run on browsers and communicate to a server that generates files that can be.
Network Programming Introduction
„Networking”.
Clients and Servers 19-Nov-18.
Programming in Java Text Books :
Clients and Servers 1-Dec-18.
Files and Streams in Java
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation transcript:

Java Programming The Language of Now & the Future Clients and Servers including Internet connectivity, I/O and JDBC John Morris and Peter Jones Department of Electrical and Electronic Engineering, University of Western Australia John Morris Peter Jones

Sockets Sockets are the “endpoints” of Internet connections Socket constructors require Internet addresses Socket( String host, int port ) throws UnknownHostException, IOException; Socket(InetAddress address, int port) throws IOException;... and a host of other alternatives, see the API documentation! Note: these constructors throw exceptions Use them in a try { } catch.. block Machine A Machine B Ports 00 nnn Internet

Sockets Note: these constructors throw exceptions Use them in a try { } catch.. Block Note: UnknownHostException is a subclass of IOException  catch( IOException e ) alone would suffice String name = new String(“ciips.ee.uwa.edu.au”); try { Socket t = new Socket( name, 80 );... } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); } catch( IOException e ) {... }

Aside: Datagrams,... Use a DatagramSocket Constructor DatagramSocket( int port ) throws IOException ; creates a datagram socket on port Methods void receive( DatagramPacket p ) throws IOException ; void send( DatagramPacket p ) throws IOException ; DatagramPacket Constructor DatagramPacket( byte[] buf, int length, InetAddress add, int port ); creates a packet to be sent to port at add Methods byte[] getData(); void setData( byte[] buf ); InetAddress getAddress();

Datagrams,... Use a DatagramSocket Constructor DatagramSocket( int port ) throws IOException ; creates a datagram socket on port Methods void receive( DatagramPacket p ) throws IOException ; void send( DatagramPacket p ) throws IOException ; DatagramPacket Constructor DatagramPacket( byte[] buf, int length, InetAddress add, int port ); creates a packet to be sent to port at add Methods byte[] getData(); void setData( byte[] buf ); InetAddress getAddress(); Note: byte[] not char[]... more later!

Multicast sockets... Messages to multiple hosts Use a MulticastSocket Constructor MulticastSocket( int port ) throws IOException; creates a datagram socket bound to port Methods void receive( DatagramPacket p ) throws IOException ; void send( DatagramPacket p ) throws IOException; void joinGroup( InetAddress mcastaddr ) throws IOException ; void leaveGroup( InetAddress mcastaddr ) throws IOException ; Hosts can join and leave multicast groups Security feature: An applet is not allowed to use a multicast socket Inherited from DatagramSocket

static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); static final String query = “?”; try { Socket server = new Socket( name, lut_port ); DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); do { output.println( query ); String resp = input.readLine(); System.out.println( name + “ response: “ + resp ); } while ( !( resp.equal( quit_string ) ) ); server.close(); } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); } catch( IOException e ) {... } Talking to a server

static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); static final String query = “?”; try { Socket server = new Socket( name, lut_port ); DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); do { output.println( query ); String resp = input.readLine(); System.out.println( name + “ response: “ + resp ); } while ( !( resp.equal( quit_string ) ) ); server.close(); } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); } catch( IOException e ) {... } Talking to a server Socket (and almost all the rest) throws an exception, so put it all in a try { } block Once the Socket has been created, create input and output streams on it DataInputStream DataOutputStream PrintStream Just part of the stream zoo - there are 55 more!

static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); static final String query = “?”; try { Socket server = new Socket( name, lut_port ); DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); do { output.println( query ); String resp = input.readLine(); System.out.println( name + “ response: “ + resp ); } while ( !( resp.equal( quit_string ) ) ); server.close(); } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); } catch( IOException e ) {... } Talking to a server Now use methods on the streams just like any other I/O device println on PrintStream readLine on DataInputStream

static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); static final String query = “?”; try { Socket server = new Socket( name, lut_port ); DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); do { output.println( query ); String resp = input.readLine(); System.out.println( name + “ response: “ + resp ); } while ( !( resp.equal( quit_string ) ) ); server.close(); } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); } catch( IOException e ) {... } Talking to a server Finally add some code to handle exceptions! Choices (Java usually gives you plenty ) ¬ Separate catch blocks for different types  One “catch all” ( IOException )  try { } catch { } for each method call ¯ Throw the exception from here

static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); static final String query = “?”; try { Socket server = new Socket( name, lut_port ); } catch( UnknownHostException e ) { System.out.println(“Unknown host:” + name ); return error_flag ; } catch( IOException e ) { /* process other errors.... */ return error_flag ; } try { DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); } catch( IOException e ) { System.out.println(“Cant form streams”); return error_flag ; } do { /* do some real work... */ Talking to a server - variant 1 Exception Choices (Java usually gives you plenty )  try { } catch { } for each method call ¯ Throw the exception from here try { } catch { } around each exception throwing call

public String ServerResp( String query ) throws IOException { static final int lut_port = 3062; String name = new String(“ciips.ee.uwa.edu.au”); Socket server = new Socket( name, lut_port ); DataInputStream input = new DataInputStream( server.getInputStream() ); PrintStream output = new PrintStream( server.getOutputStream() ); output.println( query ); String resp = input.readLine(); server.close(); return resp; } Talking to a server - variant 2 Exception Choices (Java usually gives you plenty )  try { } catch { } for each method call ¯ Throw the exception from here This method throws any exceptions up a level

static final int lut_port = 3062; static final int queue_len = 10; try { Socket server = new ServerSocket( lut_port, queue_len ); } catch( IOException e ) { System.out.println(“Can’t establish server on port “ + lut_port ); } while( true ) { // The server never dies! // Wait for a connection attempt try { Socket s = server.accept(); PrintStream ps = new PrintStream( s.getOutputStream() ); DataInputStream in = new DataInputStream( s.getInputStream() ); while( true ) { String q = in.readLine(); if ( q.equal( “?” ) ) ps.println( “Hello” ); else if ( q.equal( “quit” ) ) break; else ps.println( “??” ); } s.close(); // Close this connection } catch ( IOException e ) { /* Do something about it! */ } } Simple Server

static final int lut_port = 3062; static final int queue_len = 10; try { Socket server = new ServerSocket( lut_port, queue_len ); } catch( IOException e ) { System.out.println(“Can’t establish server on port “ + lut_port ); } while( true ) { // The server never dies! // Wait for a connection attemtp try { Socket s = server.accept(); PrintStream ps = new PrintStream( s.getOutputStream() ); DataInputStream in = new DataInputStream( s.getInputStream() ); while( true ) { String q = in.readLine(); if ( q.equal( “?” ) ) ps.println( “Hello” ); else if ( q.equal( “quit” ) ) break; else ps.println( “??” ); } s.close(); // Close this connection } catch ( IOException e ) { /* Do something about it! */ } } Simple Server Set up a ServerSocket - basically just a socket with an accept method Servers usually live forever!! The code will block here until a client attempts a connection

static final int lut_port = 3062; static final int queue_len = 10; try { Socket server = new ServerSocket( lut_port, queue_len ); } catch( IOException e ) { System.out.println(“Can’t establish server on port “ + lut_port ); } while( true ) { // The server never dies! // Wait for a connection attemtp try { Socket s = server.accept(); PrintStream ps = new PrintStream( s.getOutputStream() ); DataInputStream in = new DataInputStream( s.getInputStream() ); while( true ) { String q = in.readLine(); if ( q.equal( “?” ) ) ps.println( “Hello” ); else if ( q.equal( “quit” ) ) break; else ps.println( “??” ); } s.close(); // Close this connection } catch ( IOException e ) { /* Do something about it! */ } } Simple Server Now we just ¬ create the input & output streams ­ read and write to them ® close the connection when we’re finished

static final int lut_port = 3062; static final int queue_len = 10; try { Socket server = new ServerSocket( lut_port, queue_len ); } catch( IOException e ) { System.out.println(“Can’t establish server on port “ + lut_port ); } while( true ) { // The server never dies! // Wait for a connection attemtp try { Socket s = server.accept(); PrintStream ps = new PrintStream( s.getOutputStream() ); DataInputStream in = new DataInputStream( s.getInputStream() ); while( true ) { String q = in.readLine(); if ( q.equal( “?” ) ) ps.println( “Hello” ); else if ( q.equal( “quit” ) ) break; else ps.println( “??” ); } s.close(); // Close this connection } catch ( IOException e ) { /* Do something about it! */ } } Simple Server But... This server blocks whilst one user is using it! A second client can’t connect ‘til the first one finishes! Solution... A thread for each client

static final int lut_port = 3062; static final int queue_len = 10; try { Socket server = new ServerSocket( lut_port, queue_len ); } catch( IOException e ) { System.out.println(“Can’t establish server on port “ + lut_port ); } while( true ) { // The server never dies! // Wait for a connection attempt try { Socket s = server.accept(); // This thread will do the talking ClientHandler ch = new ClientHandler( s ); ch.start(); } catch ( IOException e ) { /* Do something about it! */ } } Multi-threaded Server Make this parameter relevant! Number of queued requests As soon as we get a connection, spawn a handler thread to talk to the client Start the thread

class ClientHandler extends Thread { Socket s; public ClientHandler( Socket s ) { this.s = s; } public void run() { PrintStream ps = new PrintStream( s.getOutputStream() ); DataInputStream in = new DataInputStream( s.getInputStream() ); while( true ) { String q = in.readLine(); if ( q.equal( “?” ) ) ps.println( “Hello” ); else if ( q.equal( “quit” ) ) break; else ps.println( “??” ); } s.close(); // Close this connection } Multi-threaded Server - The Handler Same operational code.. Just embedded in the thread’s run method Constructor - just save a reference to the socket This class is a Thread

I/O Streams - Too much choice? There’s a bewildering array of choices... “Stream Zoo” Considering input.. InputStream å ByteArrayInputStream å FileInputStream å FilterInputStream  BufferedInputStream å DataInputStream å DataInput å InflaterInputStream åGZIPInputStream åZipInputStream å... 3 more!  PipedInputStream å... 3 more! Matching Output classes also!

I/O Streams - Too much choice?... and the Reader classes! Characters (16 bits!) rather than bytes Reader å BufferedReader å LineNumberReader å CharArrayReader å FilterReader  PushbackReader å InputStreamReader å FileReader å PipedReader å StringReader Matching Writer classes also!

Writing Objects to Streams ObjectOutputStream Enables writing of serialized objects Serializable objects implement the java.io.Serializable interface private void writeObject( ObjectOutputStream out ) throws IOException; private void readObject( ObjectInputStream in ) throws IOException, ClassNotFoundException; ClassNotFoundException? A remote program could send you an object that you don’t know about.... and therefore don’t know how to de-serialize!

Bytes and characters in Java Java has Primitive types byte char Classes Byte Character Class Byte has a single attribute of type byte It’s just a class “wrapper” for a byte Class Character... Characters are Unicode characters For the full tables, see ftp://ftp.unicode.org/Public Character methods isDigit, isLetter, isLowerCase,... Full story: Gosling, Joy & Steele, “The Java Language Specification”

Bytes and characters in Java Class Character... Characters are Unicode characters Main trap... “char” files created by other programs, eg C, C++ Files created by text editors... but Windows “NotePad” often creates Unicode files for you! Suggestion Use byte / Byte if the file, stream,... may be generated/read by any other language

URLs Not surprisingly, Java provides good support for URLs URL class Constructors URL( String spec ); URL( String protocol, String host, int port, String file ); URL( String protocol, String host, String file ); Methods Object getContent(); Retrieve the whole file URLConnection openConnection(); Used when URLConnection subclasses, eg HttpURLConnection, JarURLConnection exist InputStream openStream() ;

SQL databases JDBC provides a bridge to an Open Database Connectivity (ODBC) interface to a specific database Getting started import java.sql.*; Load the bridge.. Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” ); Connect to a database Connection c = DriverManager.getConnection( String URL, String username, String passwd ); Create an SQL statement Statement s = c.createStatement(); Execute a statement s.execute( String sql_statement );

SQL databases JDBC Results from a query ResultSet res = s.executeQuery( String s ); Goto the first row... res.next(); Extract data String name = res.getString( String col_name ); int value = res.getInt( String col_name );... and, of course, several pages more! Examing the table returned ResultSetMetaData m = res.getMetaData(); Information about the table int columns = m.getColumnCount(); String label = m.getColumnLabel( int col_no ); Columns number from 1! String ctype = m.getColumnType( int col_no );... and, of course, 19 more!