Algorithm Programming 2 89-211 Network Programming Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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

Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Java Sockets Source:
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.
1 Java Networking – Part I CS , Spring 2008/9.
Moshe Fresko Bar-Ilan University
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Networking Support In Java 2 Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
COMP1681 / SE15 Introduction to Programming
Java sockets. From waiting.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
28-Jun-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
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.
Networking Support In Java 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
Process-to-Process Delivery:
Babak Esfandiari (based on slides by Qusay Mahmoud)
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Computer Networks  Network - A system of computers interconnected in order to share information.  Data transmission - consists of sending and receiving.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Appendix F: Network Programming in Java ©SoftMoore ConsultingSlide 1.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
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:
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.
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.
Network Programming With Java Hilal Arslan Hale Müge Kıncak.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
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 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.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
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.
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 Networking A network represents interconnection of computers that is capable.
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.
CHAPTER Agenda Applets Servelets Browsers HelloWorld.
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.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
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.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Working with URLs CSIE, National University of Tainan.
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.
Network Programming Communication between processes Many approaches:
Socket Programming Ameera Almasoud
Threads in Java Two ways to start a thread
Source: Java Sockets Source:
Block 15 Developing the Calculator application
MCA – 405 Elective –I (A) Java Programming & Technology
Network Programming Introduction
„Networking”.
CS18000: Problem Solving and Object-Oriented Programming
Presentation transcript:

Algorithm Programming Network Programming Bar-Ilan University תשס " ו by Moshe Fresko

Networking Basics Uses of Networks Resource Sharing High Reliability Saving Money Communication Medium Access to remote information

Network Layers Application Layer (http,ftp,telnet,smtp,dns,…) Transport Layer (TCP,UDP,…) Network Layer (IP,…) Physical + Data Link Layer (Arpanet,SatNet,Lan, …)

TCP vs UDP TCP : Transmission Control Protocol : Is a connection- based protocol that provides a reliable flow of data between two computers. Used when two applications want to communicate reliably It is Connection Based Data is get in the same order it was sent (via Streams) Transmission guarantied, or error is reported. Example: HTTP, FTP, SMTP, TELNET, UDP : User Datagram Protocol : Is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. Not connection based Communication is not guaranteed Datagram : A packet sent by UDP protocol. The order of datagrams are not guaranteed. Example: Radio, Clock Server, Ping,

IP Address IP (Internet Protocol) : Network layer protocol. IP Address : A unique 32 bit number. Dotted Decimal Notation : Range : – Every host and router in the Internet has an IP address, which encodes its network number and host number. Classes of IP Addresses Class A : 0{7 bits Network}.{24 bits Host} Class B : 10{14 bits Network}.{16 bits Host} Class C : 110{21 bits Network}.{8 bits Host} Class D : 1110{Multicast address} Class E : 11110{Reserved for future use} Special IP-addresses : This host : Broadcast on local network 127.?.?.? : Loopback

Ports Generally a computer has a single physical connection to the network. The data can be intended to different applications Port: A unique place within the machine. (Abstraction) 16 bit number Well-known ports: are reserved ports FTP is 21, TELNET 23, SMTP 25, HTTP 80, POP Custom Use > 1024 The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer

URLs URL : Uniform Resource Locater : It is a reference (an address) to a resource on the Internet. A URL has two main components Protocol Identifier Resource Name Example : http : is the Protocol Identifier //java.sun.com/ : is the Resource Name The Resource Name may contain HostName : The name of the machine FileName : The pathname of the file on the machine Port Number : The port number to which to connect (Typically Optional) Reference : A reference to a named anchor within a resource (Typically Optional)

URLs Two classes for URL processing in Java java.net.URL : Represents a URL resource java.net.URLConnection : An opened connection to a URL resource Creating an absolute URL object By Constructor : URL(String) URL myurl = new URL( “ ” ) ; Creating a URL relative to another Used for relative hyperlinks in an HTML page Presentations By Constructor : URL(URL,String) URL myurl = new URL( “ ” ) ; URL mypres = new URL(myurl, “ MyPres.html ” ) ; Other URL Constructors All constructors throw MalformedURLException URL(String protocol, String host, int port, String file) URL(String protocol, String host, String file) URL(String spec) URL(URL context, String spec)

URLs Parsing a URL String getProtocol()String getHost()int getPort() String getFile()String getRef() Example import java.net.* ; public class ParseURL { public static void main(String[]args) throws MalformedURLException { URL url = new URL(" ”books/tutorial/intro.html#DOWNLOADING") ; System.out.println("Protocol = "+url.getProtocol()) ; System.out.println("Host = "+url.getHost()) ; System.out.println("FileName = "+url.getFile()) ; System.out.println("Port = "+url.getPort()) ; System.out.println("Reference= "+url.getRef()) ; } Output Protocol = http Host = java.sun.com FileName = /docs/books/tutorial/intro.html Port = 80 Reference= DOWNLOADING

URLs Reading directly from a URL using openStream() method that returns an InputStream Example: import java.net.* ; import java.io.* ; public class URLReader { public static void main(String[] args) throws Exception { URL url = new URL(" ; BufferedReader br = new BufferedReader ( new InputStreamReader(url.openStream())) ; String line ; while ((line=br.readLine())!=null) System.out.println(line) ; br.close() ; }

URL Connection Connecting to a URL URL ’ s openConnection() method URLConnection openConnection() throws IOException ; Example: try { URL url = new URL(" ; URLConnection uc = url.openConnection() ; } catch (MalformedURLException e) { … } catch (IOException e) { … } Reading from a URL connection import java.net.* ; import java.io.* ; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL url = new URL(" ; URLConnection uc = url.openConnection() ; BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream())); String line ; while ((line=br.readLine())!=null) System.out.println(line) ; br.close() ; } }

Writing to a URLConnection Like HTML forms. In the Browser, Text fields and other GUI components that let user enter data. Browser writes the data to the URL. On the server a CGI-BIN script processes it and returns a response. Example: import java.io.* ; import java.net.* ; public class Reverse { public static void main(String[]args) throws Exception { if (args.length<1) { System.err.println("Usage: java Reverse ") ; System.exit(1) ; } String stringToReverse = URLEncoder.encode(args[0],"UTF-8") ; URL url = new URL(" ; URLConnection uc = url.openConnection() ; uc.setDoOutput(true) ; PrintWriter out = new PrintWriter(uc.getOutputStream()) ; out.println("string="+stringToReverse) ; out.close() ; BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())) ; String line ; while ((line=in.readLine())!=null) System.out.println(line) ; } }

Sockets Socket: End point of a two-way communication link between two programs running on the network. Socket is a software abstraction to represent the “ terminals ” of a connection. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Two stream-based Socket classes ServerSocket : For server On connection returns a new Socket Socket : For client Have getInputStream() and getOutputStream() functions

Socket Example – Echo import java.io.* ; import java.net.* ; public class EchoClient { public static void main(String[]args) throws IOException { Socket socket = null ; PrintWriter out = null ; BufferedReader in = null ; String host = "localhost" ; try {socket = new Socket(host,7) ;// Port number 7 out = new PrintWriter(socket.getOutputStream(),true) ; in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ; } catch (UnknownHostException e) { System.err.println("Dont know host: "+host) ; System.exit(-1) ; } catch (IOException e) { System.err.println("Cannot get IO for connection to "+host) ; System.exit(-1) ; } BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ; String input ; while ((input=stdin.readLine())!=null) { out.println(input) ; System.out.println("echo: "+in.readLine()) ; } out.close() ; in.close() ; stdin.close() ; socket.close() ;// Order important }

Socket Connection for Client Basic program flow for Client 1. Open Socket 2. Open an input stream and output stream to the socket 3. Read from and write to the stream according to the server ’ s protocol 4. Close the streams 5. Close the socket – Only step 3 differs from client to client, depending on the server

Socket Connection for Server Basic program flow for Server 1. Create a ServerSocket 2. Call ServerSocket.accept() to get a Socket connection 3. Open input stream and output stream to that socket 4. Read from and write to streams according to the Protocol 5. Close the streams 6. Close the socket 7. ( Optional: Return to 2 to get another connection ) For Server allowing multiple connections, 3-6 must be in another thread

Example: Knock Knock Example, the Knock Knock jokes Server : “ Knock! Knock! ” Client : “ Who ’ s there? ” Server: “ Dexter ” Client: “ Dexter who? ” Server: “ Dexter halls with boughs of holly ” Classes: KnockKnockProtocol : To implement the protocol KnockKnockServer : Has main method for the Server and listens to the port KnockKnockClient : Connects to the server

KnockKnockProtocol import java.net.* ; import java.io.* ; public class KnockKnockProtocol { private static final int WAITING = 0, SENTKNOCKKNOCK = 1, SENTCLUE = 2, ANOTHER = 3 ; private static final int NUMJOKES = 5 ; private int state = WAITING ; private int currentJoke = 0 ; private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" } ; private String[] answers = { "Turnip the heat, it's cold in here", "I didn't know you could yodel!", "Bless you!", "Is there an owl here?", "Is there an echo in here?" } ; public String processInput(String theInput) { String theOutput=null; if (state==WAITING) { theOutput="Knock! Knock!" ; state = SENTKNOCKKNOCK ; } else if (state==SENTKNOCKKNOCK) { if (theInput.equalsIgnoreCase("Who's there?")) { theOutput = clues[currentJoke] ; state = SENTCLUE ; } else { theOutput = "You're supposed to say 'Who's there?' Try again. Knock! Knock!" ; } } else if (state==SENTCLUE) { if (theInput.equalsIgnoreCase(clues[currentJoke]+" who?")) { theOutput = answers[currentJoke] + " Want another? (y/n)" ; state = ANOTHER ; } else { theOutput = "You're supposed to say '"+clues[currentJoke]+" who?'"+" ! Try again. Knock! Knock!" ; state = SENTKNOCKKNOCK ; } } else if (state==ANOTHER) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Knock! Knock!" ; if ((++currentJoke)==NUMJOKES) currentJoke=0 ; state = SENTKNOCKKNOCK ; } else { theOutput = "Bye." ; state = WAITING ; } } return theOutput ; } }

KnockKnockServer import java.net.* ; import java.io.* ; public class KnockKnockServer { public static void main(String[]args) throws IOException { ServerSocket serverSocket = null ; try { serverSocket = new ServerSocket(4444) ; } catch (IOException e) { System.err.println("Cannot listen on port 4444") ; 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 ; KnockKnockProtocol kkp = new KnockKnockProtocol() ; outputLine = kkp.processInput(null) ; out.println(outputLine) ; while((inputLine=in.readLine())!=null) { outputLine = kkp.processInput(inputLine) ; out.println(outputLine) ; if (outputLine.equals("Bye.")) break ; } out.close() ; in.close() ; clientSocket.close() ; serverSocket.close() ; } }

KnockKnockClient import java.io.* ; import java.net.* ; public class KnockKnockClient { public static void main(String[]args) throws IOException { Socket kkSocket = null ; PrintWriter out = null ; BufferedReader in = null ; try { kkSocket = new Socket("localhost",4444) ; out = new PrintWriter(kkSocket.getOutputStream(),true) ; in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())) ; } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost") ; System.exit(-1) ; } catch (IOException e) { System.err.println("Cannot get IO for the connection to: localhost") ; System.exit(-1) ; } BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ; String fromServer, fromUser ; while ((fromServer=in.readLine())!=null) { System.out.println("Server: "+fromServer) ; if (fromServer.equals("Bye.")) break ; fromUser = stdin.readLine() ; if (fromUser!=null) { System.out.println("Client: "+fromUser) ; out.println(fromUser) ; } } out.close() ; in.close() ; stdin.close() ; kkSocket.close() ; } }

KnockKnock Run Server Side E:\>java KnockKnockServer Client Side E:\>java KnockKnockClient Server: Knock! Knock! who is? Client: who is? Server: You're supposed to say 'Who's there?' Try again. Knock! Knock! Who's there? Client: Who's there? Server: Turnip Turnip who? Client: Turnip who? Server: Turnip the heat, it's cold in here Want another? (y/n) n Client: n Server: Bye.

Supporting Multiple Clients In the Server Side while (true) { accept a connection ; create a thread to deal with the client ; }

Server Thread - KKMultiServerThread import java.net.* ; import java.io.* ; public class KKMultiServerThread extends Thread { private Socket socket = null ; public KKMultiServerThread(Socket socket) { this.socket = socket ; } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ; PrintWriter out = new PrintWriter(socket.getOutputStream(),true) ; String inputLine, outputLine ; KnockKnockProtocol kkp = new KnockKnockProtocol() ; outputLine = kkp.processInput(null) ; out.println(outputLine) ; while ((inputLine=in.readLine())!=null) { outputLine = kkp.processInput(inputLine) ; out.println(outputLine) ; if (outputLine.equals("Bye.")) break ; } out.close() ; in.close() ; socket.close() ; } catch (IOException e) { e.printStackTrace() ; } } }

Server Class - KKMultiServer import java.net.* ; import java.io.* ; public class KKMultiServer { public static void main(String[]args) throws IOException { ServerSocket serverSocket = null ; boolean listening = true ; try { serverSocket = new ServerSocket(4444) ; } catch (IOException e) { System.err.println("Could not listen on port 4444") ; System.exit(-1) ; } while (listening) new KKMultiServerThread(serverSocket.accept()).start() ; serverSocket.close() ; }

Remote Connections Identifying a Machine IP (Internet Protocol) adress 1. DNS (Domain Name System) : 2. Dotted Quad Form : InetAddress ia=InetAddress.getByName( … ); Local Host (for testing) All these three forms connect to local host InetAddress ia=InetAddress.getByName(null) ; InetAddress ia=InetAddress.getByName( “ localhost ” ); InetAddress ia=InetAddress.getByName( “ ” ); InetAddress ia=InetAddress.getLocalHost()

Identifying a Machine import java.net.*; public class WhoAmI { public static void main(String[] args) throws Exception { if(args.length != 1) { System.err.println("Usage: WhoAmI MachineName"); System.exit(1); } InetAddress a = InetAddress.getByName(args[0]); System.out.println(a); } To run: java WhoAmI myMachine myMachine/

UDP communication UDP : Delivers independent packages whose arrival and order of arrival is not guaranteed. Packets sent by UDP protocol are called Datagrams. DataGram : Is an independent, self-contained message sent over the network whose arrival, and content are not guaranteed. Classes for UDP connection DatagramPacket DatagramSocket MulticastSocket

DatagramPacket class Constructors DatagramPacket(byte buf[], int offset, int length) DatagramPacket(byte buf[], int length) DatagramPacket(byte buf[], int offset, int length, InetAddress address, int port) DatagramPacket(byte buf[], int offset, int length, SocketAddress address) DatagramPacket(byte buf[], int length, InetAddress address, int port) DatagramPacket(byte buf[], int length, SocketAddress address) Methods void setAddress(InetAddress iaddr) InetAddress getAddress() void setSocketAddress(SocketAddress address) SocketAddress getSocketAddress() void setPort(int iport) int getPort() byte[] getData() int getOffset() int getLength() { void setData(byte[] buf, int offset, int length) void setData(byte[] buf) void setLength(int length)

Example: Quote Server - Client QuoteServer Waits to get a DataGram Reads the next line from file “ lines.txt ” Sends it as a DataGram QuoteClient Sends a DataGram to Server Listens to the Server for getting a DataGram with the Quote Lines.txt file Quote number 1. Quote number 2. Quote number 3. Quote number 4. … Run: E:\>java QuoteClient localhost Received: Quote number 1. E:\>java QuoteClient localhost Received: Quote number 2.

Example : QuoteServer import java.io.* ; import java.net.* ; import java.util.* ; public class QuoteServer { protected DatagramSocket socket = null ; protected BufferedReader in = null ; protected boolean moreQuotes = true ; public void run() throws IOException { socket = new DatagramSocket(4445) ; while (moreQuotes) { try { byte[] buf = new byte[256] ; // Request DatagramPacket packet = new DatagramPacket(buf,buf.length) ; socket.receive(packet) ; // Response String response = getNextQuote() ; buf = response.getBytes() ; // Send the response InetAddress address = packet.getAddress() ; int port = packet.getPort() ; packet = new DatagramPacket(buf,buf.length,address,port) ; socket.send(packet) ; } catch(IOException e) { e.printStackTrace() ; moreQuotes = false ; } } socket.close() ; } public QuoteServer() { try { in = new BufferedReader(new FileReader("lines.txt")) ; } catch (IOException e) { System.err.println("Cannot open file lines.txt.") ; } } public String getNextQuote() { String retVal = null ; if (in==null) { retVal = "Error in opening file." ; moreQuotes = false ; } else { try { if ((retVal=in.readLine())==null) { in.close() ; retVal = "No more quotes." ; moreQuotes = false ; } } catch (IOException e) { retVal = "Exception in server." ; moreQuotes = false ; } return retVal ; } public static void main(String[]args) throws IOException { QuoteServer qs = new QuoteServer() ; qs.run() ; }

Example: QuoteClient import java.io.* ; import java.net.* ; import java.util.* ; public class QuoteClient { public static void main(String[]args) throws IOException { if (args.length!=1) { System.err.println("Usage: java QuoteClient hostname") ; return ; } DatagramSocket socket = new DatagramSocket() ; byte[] buf=new byte[256] ; InetAddress address = InetAddress.getByName(args[0]) ; DatagramPacket packet = new DatagramPacket(buf,buf.length,address,4445) ; socket.send(packet) ; packet=new DatagramPacket(buf,buf.length) ; socket.receive(packet) ; String received=new String(packet.getData()) ; System.out.println("Received: "+received) ; socket.close() ; }

SMTP : Sending SMTP : Simple Mail Transfer Protocol A client delivers mail using a mail-server by opening a socket (TCP) connection to port 25 of it. Once the connection is made, the client sends some commands for sending messages For each command, Server sends back a message starting with a number Numbers : A successful command Numbers : Initially successful, but more information needed to complete it. Numbers , : Error

SMTP Commands HELO : Greeting from the client to server MAIL FROM: sender ’ s address RCPT TO: recipient address DATA To read the message one line at a time. “. ” to end the message Example session (may be with telnet connection) HELO 250 …. MAIL FROM: bill 250 bill … sender ok RCPT TO: mark 250 mark … Recipient ok DATA 354 Enter main, end with “. ” on a line by itself Subject: Hey there … This is a trial message. 250 VAA07456 Message accepted for delivery

POP3 protocol POP3 : Post Office Protocol version 3. Allows you to access your mailbox remotely Responses start with ‘ + ’ for successful commands ‘ - ’ in case of any error Sometimes it returns multi-line responses, that terminate with “. ” line. Usually it sits on port number 110. POP3 logging USER your_user_name PASS your_password

POP3 commands POP3 access commands STAT : Retrieves the message count LIST : Gets a list of active message numbers TOP : To examine the beginning of a message RETR : To read an entire message DELE : To delete a message Example: (Telnet session) +OK … ready USER mark +OK please send PASS command PASS abc?012 +OK 1 messages ready for mark in /usr/spool/mail/mark LIST +OK 1 messages; msg# and size for undeleted messages RETR 1 +OK message 1 ….// The whole message content. DELE 1 +OK message 1 marked for deletion LIST +OK 1 messages; msg# and size for undeleted messages. QUIT +OK … shutdown

Object Serialization Moshe Fresko Bar-Ilan University

Object Serialization To represent an object in a byte-encoded format that can be stored and passed to a stream, and in need can be reconstructed. Live Object SerializeDeSerialize Frozen Object Stream Live Object

Serialization ObjectOutputStream & ObjectInputStream Works like other input-output streams They can write and read Objects. ObjectOutputStream: Serializes Java Objects into a byte-encoded format, and writes them onto an OutputStream. ObjectInputStream: Reads and reconstructs Java Objects from a byte- encoded format read from InputStream. Serialization can be used in. Remote Method Invocation (RMI), communication between objects via sockets. (Marshaling and unmarshaling objects) Archival of an object for use in a later invocation of the same program. Objects to be serialized Must implement Serializable interface Non-persistent fields can be marked with transient keyword The following is written and read during serialization Class of the object Class signature Values of all non-transient and non-static members

Serialization To Write into an ObjectOutputStream FileOutputStream out = new FileOutputStream( “ afile ” ) ; ObjectOutputStream oos = new ObjectOutputStream(out) ; oos.writeObject( “ Today ” ) ; oos.writeObject(new Date()) ; oos.flush() ; To Read from an ObjectInputStream FileInputStream in = new FileInputStream( “ afile ” ) ; ObjectInputStream ois = new ObjectInputStream(in) ; String today = (String) ois.readObject() ; Date date = (Date) ois.readObject() ;

Serialization ObjectOutputStream.writeObject(Object) traverses all the internal references of the object recursively and writes all of them. ObjectOutputStream implements DataOutput interface to write primitive data types. writeInt( … ), writeFloat( … ), writeUTF( … ), etc. ObjectInputStream implements DataInput interface ro read primitive data types. readInt(), readFloat(), readUTF(), etc. writeObject(Object) throws NotSerializableException if Object does not implement Serializable interface

Object Serialization Example import java.io.* ; import java.util.* ; class A implements Serializable { public int i = 5 ; public String str = "Hi" ; public List l = new ArrayList() ; } public class ObjSerTest { public static void main(String[]args) { A a = new A() ; a.i = 10 ; a.str = "Hello" ; a.l.add("One") ; a.l.add("Two") ; serialize(a) ; } private static void serialize(A a) { System.out.println("Serializing..."); try { FileOutputStream fos = new FileOutputStream("test.out") ; ObjectOutputStream oos = new ObjectOutputStream(fos) ; oos.writeObject(a) ; } catch (Exception e) { System.err.println("Problem: "+e) ; } } }

Object De-serialization Example import java.io.* ; import java.util.* ; class A implements Serializable { public int i = 5 ; public String str = "Hi" ; public List l = new ArrayList() ; } public class ObjDeSerTest { public static void main(String[]args) { A a = deserialize() ; System.out.println(a.i) ; System.out.println(a.str) ; System.out.println(a.l) ; } private static A deserialize() { System.out.println("DeSerializing..."); try { FileInputStream fis = new FileInputStream("test.out") ; ObjectInputStream iis = new ObjectInputStream(fis) ; return (A) iis.readObject() ; } catch (Exception e) { System.err.println("Problem: "+e) ; } return null ; }

Customizing Serialization To define writeObject() and readObject() to append additional information. private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject() ; // customized serialization code } private void readObject(ObjectInputStream ois) throws IOException { ois.defaultReadObject() ; // customized deserialization code // if necessary, must include code to update the object }

Externalizable interface To control the serialization process explicitly, Externalizable interface must be implemented. Externalizable interface public interface Externalizable extends Serializable { public void writeExternal(ObjectOutput out) throws IOException ; public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException ; } writeExternal and readExternal must save/load the state of the object. They must explicitly coordinate with its supertype to save its state.

Java Applets Moshe Fresko Bar-Ilan University

Java Applets Applet: A Java program that adheres to certain conventions that allow it to be included in HTML pages and executed within Java-enabled browsers. Compiled with regular JDK compiler (javac). Can be checked by Applet Viewer program (appletviewer). It can be included in an HTML to be run within a browser.

Example Applet HelloWorld.java import java.applet.Applet ; import java.awt.Graphics ; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello World!",50,25) ; } Hello.html A Simple Program Here is the output of the program: To Compile: javac HelloWorld.java To run: Either: To load Hello.html from a Java available browser Or: To run: AppletViewer Hello.html

Applet class Hierarchy java.lang.Object java.awt.Component java.awt.Container java.applet.Applet javax.swing.JApplet One Applet Class Another Applet Class

A Simple Applet import java.applet.Applet ; import java.awt.Graphics ; public class Simple extends Applet { StringBuffer buffer ; public void init() { buffer = new StringBuffer() ; addItem("initializing... ") ; } public void start() { addItem("starting... ") ; } public void stop() { addItem("stopping... ") ; } public void destroy() { addItem("preparing for unloading... ") ; } void addItem(String aWord) { System.out.println(aWord) ; buffer.append(aWord) ; repaint() ; } public void paint(Graphics g) { g.drawRect(0,0,getSize().width-1,getSize().height-1) ; g.drawString(buffer.toString(),5,15) ; } }

Life Cycle of an Applet Loading the Applet An instance of the applet ’ s subclass is created. (new MyApplet() ) The applet initializes itself (calls.init() method) The applet starts running (calls.start() method) Leaving and Returning to the Applet ’ s page. When user leaves the page applet is stopped, and when the user returns to the page it is restarted. These processed are also done when the browser window is minimized and restored. Reloading the Applet Previous applet is stopped. Some final clean-ups are done. Then a new instance is loaded. Quitting the Browser Applet is stopped and some final clean-ups are done.

Applet Mile-Stone methods init() : Automatically called to perform first-time initialization of the applet. start() : Called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations. Also called after init( ). stop() : Called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ). destroy() : Called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used

Methods for Drawing Method for Drawing paint(Graphics g) : Applets implement the paint method to draw the applet ’ s representation within a browser window. update(Graphics g) : A method that can be used with paint to improve drawing performance. Methods for Adding UI Components add( … ) : Adds the specified Component to the applet. remove( … ) : Removes the specified Component setLayout( … ) : Sets the applets layout manager Methods for drawing and event handling add???Listenet(???Listener) : Like in the regular Graphical Components

Event Handling in Applets import java.applet.Applet ; import java.awt.Graphics ; import java.awt.event.* ; public class SimpleEvent extends Applet { StringBuffer buffer ; public void init() { buffer = new StringBuffer() ; addMouseListener(new MyMouseListener()) ; addItem("initializing... ") ; } class MyMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent event) { addItem("Click!...") ; } } public void start() { addItem("starting... ") ; } public void stop() { addItem("stopping... ") ; } public void destroy() { addItem("preparing for unloading... ") ; } void addItem(String aWord) { System.out.println(aWord) ; buffer.append(aWord) ; repaint() ; } public void paint(Graphics g) { g.drawRect(0,0,getSize().width-1,getSize().height-1) ; g.drawString(buffer.toString(),5,15) ; } }

JApplet to GUI components JApplet is the swing version of Applet. The GUI component is added to the internal container by using getInternalPane() method.

JApplet example import javax.swing.*; import java.awt.event.*; import java.awt.*; // public class ButtonsApplet extends JApplet { private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String name = ((JButton)e.getSource()).getText(); txt.setText(name); } } private ButtonListener bl = new ButtonListener(); public void init() { b1.addActionListener(bl); b2.addActionListener(bl); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(b1); cp.add(b2); cp.add(txt); }

Applet Restrictions Arbitrary Applets loaded from the Net has maximal restrictions. Browser can give to some Applets more access permissions. Like: Applets with certain signatures Applets loaded from a trusted url. Security Checking: Each browser has a SecurityManager object that checks for applet security violations on potentially troublesome operations. When a SecurityManager detects a violation, it throws SecurityException. Common Restrictions: To load libraries or define native methods. To read or write files on the host executing it. To make network connections. (Except the host from which it came) To start another program on the host executing it To get some system properties

Applet API getCodeBase() : Returns the URL of the directory from which the applet ’ s classes were loaded. getDocumentBase() : Returns the URL of the directory of the HTML page that contains the applet. AppletContext getAppletContext() AppletContext.showStatus(String) : Displays String in Status line. AppletContext.showDocument(java.net.URL) : AppletContext.showDocument(java.net.URL,String targetWindow) : Tells browser to display the given URL ’ s content. AppletContext.getApplet(String appletName) : Returns the Applet object from the current page for the given name. AppletContext.getApplets(String appletName) : Returns the Applets of the page as an Enumeration of Applet objects.

Applet API – via AppletContext showStatus(String) : Displays String in Status line. showDocument(URL) : showDocument(URL,String targetWindow) : Tells browser to display the given URL ’ s content. getApplet(String appletName) : Returns the Applet object from the current page for the given name. getApplets(String appletName) : Returns the Applets of the page as an Enumeration of Applet objects. AudioClip getAudioClip(URL) AudioClip getAudioClip(URL,String)

Applet – Passing parameters String getParameter(String name) : Returns the value of the parameter as a string.