Java API Essentials (Part II) Web Languages Course 2009 University of Trento

Similar documents
Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

Lesson: All About Sockets

Java Network. Slides prepared by : Farzana Rahman

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Application Development with TCP/IP. Brian S. Mitchell Drexel University

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Network/Socket Programming in Java. Rajkumar Buyya

Creating a Simple, Multithreaded Chat System with Java

Socket Programming in Java

Division of Informatics, University of Edinburgh

Socket-based Network Communication in J2SE and J2ME

Network Communication

Slides for Chapter 4: Interprocess Communication

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Advanced Network Programming Lab using Java. Angelos Stavrou

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Java Programming: Sockets in Java

Network Programming using sockets

Assignment 4 Solutions

Socket Programming. Announcement. Lectures moved to

Corso di Reti di Calcolatori

Building a Multi-Threaded Web Server

Socket programming. Complement for the programming assignment INFO-0010

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users

Corso di Reti di Calcolatori. java.net.inetaddress

Data Communication & Networks G

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Manual. Programmer's Guide for Java API

JAVA Program For Processing SMS Messages

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

public static void main(string[] args) { System.out.println("hello, world"); } }

Mail User Agent Project

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

Threads & Tasks: Executor Framework

OBJECT ORIENTED PROGRAMMING LANGUAGE

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

INPUT AND OUTPUT STREAMS

JAVA - MULTITHREADING

Threads in der Client/Server-Programmierung mit Java

An Android-based Instant Message Application

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Multithreaded Programming

!"# $ %!&' # &! ())*!$

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

CS11 Java. Fall Lecture 7

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

Java from a C perspective. Plan

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

When the transport layer tries to establish a connection with the server, it is blocked by the firewall. When this happens, the RMI transport layer

CS506 Web Design and Development Solved Online Quiz No. 01

An Overview of Java. overview-1

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Transparent Redirection of Network Sockets 1

Building a Java chat server

Fundamentals of Java Programming

CISC 4700 L01 Network & Client- Server Programming Spring Harold, Chapter 8: Sockets for Clients

ExempleRMI.java. // Fichier de defintion des droits et proprietes // System.setProperty("java.security.policy","../server.java.

Communicating with a Barco projector over network. Technical note

Java Interview Questions and Answers

What is an I/O Stream?

Chapter 8 Implementing FSP Models in Java

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

XII. Distributed Systems and Middleware. Laurea Triennale in Informatica Corso di Ingegneria del Software I A.A. 2006/2007 Andrea Polini

D06 PROGRAMMING with JAVA

Lecture 7: Java RMI. CS178: Programming Parallel and Distributed Systems. February 14, 2001 Steven P. Reiss

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Transparent Redirection of Network Sockets 1

Crash Course in Java

Input / Output Framework java.io Framework

13 File Output and Input

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

race conditions Image courtesy of photostock / FreeDigitalPhotos.net Flavia Rainone - Principal Software Engineer

WRITING DATA TO A BINARY FILE

CHAPTER 6. Transmission Control Protocol. 6.1 Overview

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Sockets. Programação de Sockets em Java. Socket Abstractions. Camada de Transporte

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

Report of the case study in Sistemi Distribuiti A simple Java RMI application

Files and input/output streams

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

CS 1302 Ch 19, Binary I/O

Lecture J - Exceptions

Preface. Intended Audience

ELEN 602: Computer Communications and Networking. Socket Programming Basics

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

Java SE 8 Programming

Event-Driven Programming

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Web Services in.net (1)

Socket Programming. A er learning the contents of this chapter, the reader will be able to:

The Interface Concept

Remote Method Invocation

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute

Transcription:

Java API Essentials (Part II) Web Languages Course 2009 University of Trento

Lab Objective More exercises on Object serialization Client-Server application through sockets Refresh basic Java concepts on Threads Exercise on threads The TCPPortScanner application 2

The java.net package The package java.net provides support for sockets programming The package java.net contains: Socket, URL, InetAddress, ServerSocket, etc. Sockets + Object Serialization: combine java.net and java.io.serializable to transport Java objects through the network 3

Sockets Endpoint of a two-way communication link between two programs running on the network. An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. 4

TCP Sockets Connection-oriented sockets, almost always based on TCP java.net.serversocket Implements the server side of the connection Used to listen for connection requests from clients; Should be bound to a known port to listen on, Its accept method blocks until a client requests a connection java.net.socket Implements the client side of the connection Used to connect to a specific port in a server machine 5

Socket TCP Constructor Socket(String host, int port) Socket(InetAddress address, int port) ServerSocket(int port) ServerSocket(int port, int backlog ) Create a stream socket and connects it to the specified port number on the named host. a stream socket and connects it to the specified port number at the specified IP address a server socket, bound to the specified port. a server socket and binds it to the specified local port number, with the specified backlog (maximum queue length for incoming connection) 6

Socket Timeout If data are not available (e.g., the host is not reachable), the reading methods remain blocked To solve the problem: use the setsotimeout() method Socket s = new Socket( ); s.setsotimeout(1000); //time out in millisecond When a timeout is set, all the following operations throw the exception InterruptedIOException 7

try { EchoClient //Create connection to the server "localhost" on port 8189 s = new Socket("localhost",8189); //Set streams to read from and write to a socket s_in = new BufferedReader(new InputStreamReader(s.getInputStream())); s_out = new PrintWriter(s.getOutputStream(),true); System.out.println(s_in.readLine()); //Set input stream for reading from console console = new BufferedReader(new InputStreamReader(System.in)); String user_input; String received; while(true){ user_input = console.readline(); s_out.println(user_input); received = s_in.readline(); System.out.println(received); 8

EchoServer try { ServerSocket s = new ServerSocket (8189); //Wait for the client Socket client = s.accept(); System.out.println( Connection requested from host: " + incoming.getinetaddress().gethostname() + "\nto port: " + incoming.getlocalport() + "\nfrom port: " + incoming.getport() + "\nwith IP: " + incoming.getinetaddress().gethostaddress()); BufferedReader in = new BufferedReader (new InputStreamReader (incoming.getinputstream ())); PrintWriter out = new PrintWriter (incoming.getoutputstream (), true); out.println ("Hello! Enter BYE to exit."); 9

EchoServer boolean go = true; String line; while (go){ line = in.readline (); out.println ("Echo: " + line); if (line.trim().equals("bye")){ go = false; incoming.close () catch (IOException e) { System.out.println ("Error. " + e); 10

Exercises (15 min.) 1. Test EchoServer.java and EchoClient.java: use the client EchoClient.java to invoke the service provided by EchoServer.java 2. Write a client-server application so that when the client connect to the server, the server replies by sending a Date object to the client (Object Serialization through sockets) 11

TCP client example makes connection to server, sends request and receives reply import java.net.*; import java.io.*; public class TCPClient { public static void main (String args[]) { // arguments supply message and hostname of destination Socket s = null; try{ int serverport = 7896; s = new Socket(args[1], serverport); ObjectInputStream in = new ObjectInputStream( s.getinputstream()); ObjectOutputStream out = new ObjectOutputStream( s.getoutputstream()); out.writeutf(args[0]); Or with timeout: s = new Socket(); s.connect(new InetSocketAddress(host, port), timeout); blocking (timeout) Error Handling String data = in.readutf(); System.out.println("Received: + data) ; catch (UnknownHostException e){ System.out.println("Sock:"+e.getMessage()); catch (EOFException e){system.out.println("eof:"+e.getmessage()); catch (IOException e){system.out.println("io:"+e.getmessage()); finally {if(s!=null) try {s.close();catch (IOException e) {System.out.println("close:"+e.getMessage()); 12

Exercise (15 min.) 3. Write a client-server application so that: The client process (StringClient.java) : - Creates an ArrayList object and fill it with 3-5 String object - Displays the content of the object - Sends the object to the server - Receives an object from the server - Displays the content of the object received The server process (StringServer.java): - Receives an ArrayList object from the client - Reverts the strings contained in the object received - Creates a new ArrayList object filled with the reversed strings - Sends the object created to the client 13

Java Threads The package java.lang.*

Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that seem to perform multiple tasks at the same time (e.g. multi-threaded Web servers) A new way to think about programming 15

How to create Java Threads There are two ways to create a Java thread: 1. Extend the java.lang.thread class 2. Implement the java.lang.runnable interface 16

Extending the Thread class In order to create a new thread we may subclass java.lang.thread and customize what the thread does by overriding its empty run method. The run method is where the action of the thread takes place. The execution of a thread starts by calling the start method. 17

Example I 1 public class MyThread extends Thread { private String name, msg; public MyThread(String name, String msg) { this.name = name; this.msg = msg; public void run() { System.out.println(name + " starts its execution"); for (int i = 0; i < 5; i++) { System.out.println(name + " says: " + msg); try { Thread.sleep(5000); catch (InterruptedException ie) { System.out.println(name + " finished execution"); 18

Example I 2 public class Test1 { public static void main(string[] args) { MyThread mt1 = new MyThread("thread1", "ping"); MyThread mt2 = new MyThread("thread2", "pong"); mt1.start(); mt2.start(); The threads run in parallel 19

Example I 3 Typical output of the previous example: thread1 starts its execution thread1 says: ping thread2 starts its execution thread2 says: pong thread1 says: ping thread2 says: pong thread1 says: ping thread2 says: pong thread1 says: ping thread2 says: pong thread1 says: ping thread2 says: pong thread1 finished execution thread2 finished execution 20

Implementing the Runnable interface In order to create a new thread we may also provide a class that implements the java.lang.runnable interface Preferred way in case our class has to subclass some other class The thread s logic is included inside the run method of the runnable object 21

Example II 1 public class MyClass implements Runnable { private String name; private A sharedobj; public MyClass(String name, A sharedobj) { this.name = name; this.sharedobj = sharedobj; public void run() { System.out.println(name + " starts execution"); for (int i = 0; i < 5; i++) { System.out.println(name + " says: " + sharedobj.getvalue()); try{ Thread.sleep(5000); catch (InterruptedException ie) { System.out.println(name + " finished execution"); 22

Example II 2 public class A { private String value; public A(String value) { this.value = value; public String getvalue() { return value; public class Test2 { public static void main(string[] args) { A sharedobj = new A("some value"); Thread mt1 = new Thread(new MyClass("thread1", sharedobj)); Thread mt2 = new Thread(new MyClass("thread2", sharedobj)); mt1.start(); mt2.start(); Shared variable 23

Example II 3 Typical output of the previous example: thread1 starts execution thread1 says: some value thread2 starts execution thread2 says: some value thread1 says: some value thread2 says: some value thread1 says: some value thread2 says: some value thread1 says: some value thread2 says: some value thread1 says: some value thread2 says: some value thread1 finished execution thread2 finished execution 24

Supporting Multiple Connection 1 makes a connection for each client and then echoes the client s request import java.net.*; import java.io.*; public class TCPServer { public static void main (String args[]) { try{ Or: Connection c = new Connection(clientSocket); c.start(); int serverport = 7896; ServerSocket listensocket = new ServerSocket(serverPort); while(true) { Socket clientsocket = listensocket.accept(); (new Thread(new Connection(clientSocket))).start(); catch(ioexception e){s System.out.println("Listen :"+e.getmessage()); 25

Supporting Multiple Connection 2 makes a connection for each client and then echoes the client s request public class Connection implements Runnable{ ObjectInputStream in; ObjectOutputStream out; Socket clientsocket; public Connection (Socket s) { try { clientsocket = s; in = new ObjectInputStream( s.getinputstream()); out = new ObjectOutputStream( s.getoutputstream()); catch(ioexception e) {System.out.println("Connection: + e.getmessage()); public void run(){ try {// an echo server String data = in.readobject(); out.writeobject(data); catch(ioexception e){ System.out.println("IO:"+e.getMessage()); 26

Exercises (15 min.) 4. Modify the server code of the previous exercises (EchoServer.java, DateServer, RevertStringServer) so that it can accept multiple connections (a thread is started once a connection is opened) 27

Synchronization of Threads 1 In many cases concurrently running threads share data and must consider the state and activities of other threads If two threads can both execute a method that modifies the state of an object then the method should be declared to be synchronized, allowing only one thread to execute the method at a time. If a class has at least one synchronized methods, each instance of it has a monitor. A monitor is an object that can block threads and notify them when it is available. 28

Synchronization of Threads 2 Example: public synchronized void updaterecord() { // critical code goes here Only one thread may be inside the body of this function. A second call will be blocked until the first call returns or wait() is called inside the synchronized method. 29

Synchronization of Threads 3 The Thread class has a method, join(), which allows an object to wait until the thread terminates public void mymethod() { // Do some work here... //Can't proceed until another thread is done: otherthread.join(); //Continue work... 30

Summary Exercise TCP PortScanner

Summary Exercise: TCPPortScanner Realize an application which : Scans all ports (from number X to number Y) of a specific host, with only one thread of execution Scans the same ports in parallel, by using N threads Stores log info into a log file (or console) Stores the scan results into a file Check and prints the execution time in both cases (single thread and parallel threads) Assumptions: Scanning a port means checking if the given port is open or not to a socket connection; Y is greater than X N is minor or equal to Y-X; N, X e Y can be specified as input parameters 32

TCPPortScanner : Expected Output ----- Port Scanning Report ----- Date: Sun Feb 24 21:47:20 CET 2008 Scanned Host: localhost From port: 1 To port: 10 Execution Time (1 thread): 7 sec Execution Time (3 threads): 1 sec Port State 1 OPEN 2 CLOSED 3 CLOSED 4 CLOSED 5 OPEN 6 CLOSED 7 CLOSED 8 OPEN 9 CLOSED 10 CLOSED 33

TCPPortScanner : Log Info Thread-0 SCANNING PORT: 2 Thread-0 SCANNING PORT: 3 Thread-0 SCANNING PORT: 10 port per Threads: 3 left Ports: 1 Thread: 0 from 1 to 3 Thread: 1 from 4 to 6 Thread: 2 from 7 to 10. Thread-3 SCANNING PORT: 7 Thread-3 SCANNING PORT: 8 Thread-1 SCANNING PORT: 2 Thread-2 SCANNING PORT: 5 Thread-3 SCANNING PORT: 9 Thread-1 SCANNING PORT: 3 Thread-2 SCANNING PORT: 6 Thread-3 SCANNING PORT: 10 34

References http://java.sun.com/docs/books/tutorial/essential/con currency/ 35