TCP Sockets. Multithreading. But first... Overview of Multithreading in Java. Background on Threads

Similar documents
Socket Programming in Java

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

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

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Assignment 4 Solutions

Java Network. Slides prepared by : Farzana Rahman

Creating a Simple, Multithreaded Chat System with Java

Java Programming: Sockets in Java

Socket-based Network Communication in J2SE and J2ME

Lesson: All About Sockets

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

Division of Informatics, University of Edinburgh

Network Models OSI vs. TCP/IP

Network/Socket Programming in Java. Rajkumar Buyya

Preface. Intended Audience

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

Building a Multi-Threaded Web Server

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

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

Network Communication

Corso di Reti di Calcolatori. java.net.inetaddress

Corso di Reti di Calcolatori

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

Domain Name System (DNS) Omer F. Rana. Networks and Data Communications 1

JAVA Program For Processing SMS Messages

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

An Overview of Java. overview-1

Advanced Network Programming Lab using Java. Angelos Stavrou

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

Crash Course in Java

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

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

Application-layer Protocols

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

INPUT AND OUTPUT STREAMS

Threads & Tasks: Executor Framework

Socket Programming. Announcement. Lectures moved to

Fundamentals of Java Programming

AVRO - SERIALIZATION

CS506 Web Design and Development Solved Online Quiz No. 01

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

Java Interview Questions and Answers

An Introduction to Network Programming with Java

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

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

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

Introduktion til distribuerede systemer uge 37 - fil og webserver

CHAPTER 6. Transmission Control Protocol. 6.1 Overview

Communicating with a Barco projector over network. Technical note

Socket programming. Complement for the programming assignment INFO-0010

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

OBJECT ORIENTED PROGRAMMING LANGUAGE

Building a Java chat server

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

An Android-based Instant Message Application

Files and input/output streams

Network Programming using sockets

Network-based Applications. Pavani Diwanji David Brown JavaSoft

J a v a Quiz (Unit 3, Test 0 Practice)

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

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

Manual. Programmer's Guide for Java API

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

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

Transparent Redirection of Network Sockets 1

Remote Method Invocation

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

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

AP Computer Science Java Subset

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

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Java Programming Language

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

JAVA - MULTITHREADING

Mail User Agent Project

Java CPD (I) Frans Coenen Department of Computer Science

WRITING DATA TO A BINARY FILE

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

D06 PROGRAMMING with JAVA

Web Development in Java

B.Sc (Honours) - Software Development

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

Java from a C perspective. Plan

Transparent Redirection of Network Sockets 1

CS 111 Classes I 1. Software Organization View to this point:

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

ODROID Multithreading in Android

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

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

Programmation 2. Introduction à la programmation Java

Java SE 8 Programming

Event-Driven Programming

Java Memory Model: Content

Stream Classes and File I/O

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

CS11 Java. Fall Lecture 7

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Contents. 9-1 Copyright (c) N. Afshartous

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

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Transcription:

But first... Background on Threads Overview of Multithreading in Java Multithreading Java has build-in support for concurrent programming. This enables you to have multiple flows of control, represented by multiple threads within a single program (process). A thread is a single sequential flow of control within a process. Each thread has a separate execution path, with its own beginning, program flow, current point of execution, and end. They are represented by Thread objects in Java.

Multithreading (Contd.) Multithreading allows a program to perform multiple tasks concurrently. Although threads give the appearance of running concurrently, in a single- processor system the interpreter is switching between the threads and running them one at a time. Multiprocessor systems may actually run multiple threads concurrently. The threads all run in the same memory space, i.e., they can all access the same memory and call methods as if they were in a normal singlethreaded process. Why Threads? Threads are useful whenever you have multiple tasks that you want to run concurrently. For example, consider a program that interactively reacts with the user, and that also needs to download a file over the networks. The Thread Class Creating Threads You create and manipulate threads in Java using instances of the Thread class. One way to use threads is to subclass Thread, and override its run() method. The run() method is the heart of the Thread object. It should contain code to do whatever work the object needs to do. class FileDownload extends Thread // code to download file The Thread class in defines in java.lang package. Creating the thread is done by creating an instance of the new class. You then invoke the start() method, inherited from Thread. start() automatically invokes run(), and then returns control immediately. run() will now execute in a separate thread. FileDownload fd = new FileDownload(); fd.start(); // Returns control immediately // Do whatever else you want to do // e.g., continue to interact with user The new thread runs until its run() method finishes, or until you stop it explicitly.

The Runnable Interface A Simple Example You can also use classes that implement the Runnable interface to run code in separate threads. The Runnable interface simply declares the run() method. It is also defined in the java.lang package. class FileDownload implements Runnable // Code to download file To run the code is a separate thread, create an instance of Thread, with an instance of the Runnable as an argument to its constructor. Starting the thread with then cause the Runnable s run() method to be executed. Thread t = new Thread( new FileDownload() ); t.start(); // Calls FileDownload s run() method This allows to have code executed in a thread without needing to subclass Thread. This is useful if you need to subclass a different class to get other functionality (e.g., the Applet class). // Define a class that extends Thread class LoopThread extends Thread // Define its run() method to do what you want for(int i=1; i <= 20; i++) System.out.println( I am loopy ); public class Looper public static void main(string[] args) // Create an instance of the thread LoopThread loopy = new LoopThread(); // Start it up loopy.start(); JAVA - Internet Addresses java.net.inetaddress class You get an address by using static methods: Create InetAddress object representing the local machine InetAddress myaddress = InetAddress.getLocalHost(); Create InetAddress object representing some remote machine InetAddress ad = InetAddress.getByName(hostname);

JAVA - Printing Internet Addresses You get information from an InetAddress by using methods: ad.gethostname(); ad.gethostaddress(); JAVA - The InetAddress Class Handles Internet addresses both as host names and as IP addresses Static Method getbyname returns the IP address of a specified host name as an InetAddress object Methods for address/name conversion: public static InetAddress getbyname(string host) throws UnknownHostException public static InetAddress[] getallbyname(string host) throws UnknownHostException public static InetAddress getlocalhost() throws UnknownHostException public boolean ismulticastaddress() public String gethostname() public byte[] getaddress() public String gethostaddress() public int hashcode() public boolean equals(object obj) public String tostring() The Java.net.Socket Class Connection is accomplished through the constructors. Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object. public Socket(String host, int port) throws UnknownHostException, IOException public Socket(InetAddress address, int port) throws IOException public Socket(String host, int port, InetAddress localaddress, int localport) throws IOException public Socket(InetAddress address, int port, InetAddress localaddress, int localport) throws IOException Sending and receiving data is accomplished with output and input streams. There are methods to get an input stream for a socket and an output stream for the socket. public InputStream getinputstream() throws IOException public OutputStream getoutputstream() throws IOException There is a method to close a socket: public void close() throws IOException The Java.net.ServerSocket Class The java.net.serversocket class represents a server socket. It is constructed on a particular port. Then it calls accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept() returns a java.net.socket object that is used to perform the actual communication with the client. public ServerSocket(int port) throws IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress bindaddr) throws IOException public Socket accept() throws IOException public void close() throws IOException [BLOCKING]

SERVER: 1. Create a ServerSocket object ServerSocket servsocket = new ServerSocket(1234); 2. Put the server into a waiting state Socket link = servsocket.accept(); //BLOCKING 3. Set up input and output streams 4. Send and receive data out.println(data); String input = in.readline(); 5. Close the connection link.close() Set up input and output streams Once a socket has connected you send data to the server via an output stream. You receive data from the server via an input stream. Methods getinputstream and getoutputstream of class Socket: BufferedReader in = new BufferedReader( new InputStreamReader(link.getInputStream())); PrintWriter out = new PrintWriter(link.getOutputStream(),true); CLIENT: 1. Establish a connection to the server Socket link = new Socket(inetAddress.getLocalHost(), 1234); 2. Set up input and output streams 3. Send and receive data 4. Close the connection References Cisco Networking Academy Program (CCNA), Cisco Press. CSCI-5273 : Computer Networks, Dirk Grunwald, University of Colorado-Boulder CSCI-4220: Network Programming, Dave Hollinger, Rensselaer Polytechnic Institute. TCP/IP Illustrated, Volume 1, Stevens. Java Network Programming and Distributed Computing, Reilly & Reilly. Computer Networks: A Systems Approach, Peterson & Davie. http://www.firewall.cx http://www.javasoft.com