Socket-based Network Communication in J2SE and J2ME

Similar documents
Socket Programming in Java

Network Communication

Java Network. Slides prepared by : Farzana Rahman

NETWORK PROGRAMMING IN JAVA USING SOCKETS

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

Creating a Simple, Multithreaded Chat System with Java

Network/Socket Programming in Java. Rajkumar Buyya

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

Building a Multi-Threaded Web Server

Network Programming using sockets

Lesson: All About Sockets

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

Network-based Applications. Pavani Diwanji David Brown JavaSoft

Data Communication & Networks G

Division of Informatics, University of Edinburgh

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

Java Programming: Sockets in Java

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

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

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

Socket Programming. Announcement. Lectures moved to

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

Assignment 4 Solutions

Transparent Redirection of Network Sockets 1

SSC - Communication and Networking Java Socket Programming (II)

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

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

Socket programming. Complement for the programming assignment INFO-0010

Threads & Tasks: Executor Framework

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

Mail User Agent Project

JAVA Program For Processing SMS Messages

Communicating with a Barco projector over network. Technical note

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

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

Transparent Redirection of Network Sockets 1

An Android-based Instant Message Application

Multithreaded Programming

An Overview of Java. overview-1

Operating Systems Design 16. Networking: Sockets

Lecture 2-ter. 2. A communication example Managing a HTTP v1.0 connection. G.Bianchi, G.Neglia, V.Mancuso

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

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

JAVA - MULTITHREADING

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

CS11 Java. Fall Lecture 7

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

INPUT AND OUTPUT STREAMS

TCP/IP - Socket Programming

Outline of this lecture G52CON: Concepts of Concurrency

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

Building a Java chat server

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

Chapter 3. Internet Applications and Network Programming

Transport Layer Protocols

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

Network Programming. Writing network and internet applications.

Intranet, Extranet, Firewall

It is the thinnest layer in the OSI model. At the time the model was formulated, it was not clear that a session layer was needed.

Manual. Programmer's Guide for Java API

Java Interview Questions and Answers

CS506 Web Design and Development Solved Online Quiz No. 01

What is an I/O Stream?

Logging in Java Applications

Java Concurrency Framework. Sidartha Gracias

Socket Programming in C/C++

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

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

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab.

Files and input/output streams

Fundamentals of Java Programming

Mutual Exclusion using Monitors

Implementing Network Software

Chapter 8 Implementing FSP Models in Java

Note! The problem set consists of two parts: Part I: The problem specifications pages Part II: The answer pages

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

Chapter 6 Concurrent Programming

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

Threads 1. When writing games you need to do more than one thing at once.

AP Computer Science Java Subset

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

AVRO - SERIALIZATION

WRITING DATA TO A BINARY FILE

JAVA - FILES AND I/O

Java Memory Model: Content

Disfer. Sink - Sensor Connectivity and Sensor Android Application. Protocol implementation: Charilaos Stais (stais AT aueb.gr)

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

Event-Driven Programming

OBJECT ORIENTED PROGRAMMING LANGUAGE

Remote Method Invocation

Crash Course in Java

Java Programming Unit 10. Stock Price Quotes with URL, Sockets, and RMI

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Monitors, Java, Threads and Processes

Socket Programming. Srinidhi Varadarajan

Java from a C perspective. Plan

Transcription:

Socket-based Network Communication in J2SE and J2ME 1

C/C++ BSD Sockets in POSIX POSIX functions allow to access network connection in the same way as regular files: There are special functions for opening the connections, the connection is known in POSIX as socket and may be used for different types of communication inter-process communication on the same machine, different network protocols, etc. Socket- and protocol-specific parameters are set and retrieved by calling special functions Data transfer is done by specific functions or in regular way (read, write) J2SE copies this approach in Object-oriented way to a degree (methods have similar/same names as POSIX functions). 2

Stream Communication (TCP) socket bind connect client server listen accept DATA send/recv close 3

Datagram Communication (UDP) socket bind connect (a) (b) send/recv read/write (a) DATA close (b) sendto/recvfrom 4

J2SE TCP/IP Communication (1) Network communication classes in J2SE can be found in java.net namespace. However, many related classes do not have a common parent other then Object: java.net.socket basic client socket for TCP connection. Used to access remote services; we usually supply destination address and port in constructor: new Socket(host, port); java.net.datagramsocket socket for sending and receiving UDP datagrams, we supply local port in constructor when necessary: new DatagramSocket(host, port); java.net.multicastsocket DatagramSocket used for sending multicasts (traffic to a group of computers). java.net.datagrampacket block of data to send/receive with DatagramSocket. We wrap it around a buffer in constructor and if necessary specify an InetAddress and port of destination computer: new DatagramPacket(buffer, length, [address, [port]]);

J2SE TCP/IP Communication (2) java.net.inetaddress representation of IP address. Instance can be created by static methods getbyname(hostname), getbyaddress(byte[4] addr). Text representation of IP address can be retrieved back by gethostaddress() and gethostname(). java.net.serversocket basic server socket for TCP connection. We need to specify at least the local port the server will be listening at and number of queued requests: new ServerSocket(port [, backlog]); When we want to retrieve a queued connection, we call the listen() method on server socket. java.net.url class representing the URL, usually "http://...". java.net.urlconnection basic abstract class for URL-based connections. Corresponding sub-class is opened using call to new URL(url).openConnection(); 6

J2SE Sockets Remarks The socket operations are blocking, i.e. the thread execution will stop until the socket operation is finished. Since non-blocking sockets do not exist in Java, we can use a workaround by calling setsotimeout(ms). In case the timeout is reached, java.net.sockettimeoutexception is thrown and can be caught. Several connection/socket parameters can be set/retrieved by calling various set*/get* methods. Both connect and bind methods can be called, if we do not specify the needed parameters in constructor, but we need to specify an InetAddress + port or SocketAddress 7

J2SE TCP Socket Connection The Socket allows us to connect to given port on a given host. try { s=new Socket(host,port); BufferedReader sis = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter os = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader is = new BufferedReader(new InputStreamReader(s.getInputStream())); String l; do { System.out.println("Type a line to send to server."); l=sis.readline(); os.write(l); os.newline(); os.flush(); System.out.println("Server: " + is.readline()); while (!l.equals("exit") &&!l.equals("down")); s.close(); catch (IOException e) { System.out.println(e);

J2SE TCP Server The ServerSocket listens to traffic on given port on localhost. The accept() method returns a socket representing client side. try { ServerSocket s=new ServerSocket(port); Socket cs; do { cs=s.accept(); BufferedReader is = new BufferedReader (new InputStreamReader(cs.getInputStream())); BufferedWriter os = new BufferedWriter (new OutputStreamWriter(cs.getOutputStream())); do { msg=is.readline(); os.write(string.valueof(msg.length())); os.newline(); os.flush(); while (!msg.equals("exit") &&!msg.equals("down")); cs.close(); while (!msg.equals("down")); s.close(); catch (IOException e) { System.out.println(e);

J2SE TCP Server MultiThreading Since all requests in previous example must wait until the server calls accept again, the processing is delayed. The solution is to use Threads: public class MyApplication implements Runnable { protected Socket cs; static ServerSocket s; static int port=8000; public static void main(string[] args) { Socket cs; try { s=new ServerSocket(port); do {cs=s.accept(); new Thread(MyApplication(cs)).start(); while (true); catch (IOException e) {if(!e instanceof SocketException){System.out.println(e); public MyApplication(Socket cs) {this.cs=cs; public void run() { /* Violet bold text from previous slide */ if (msg.equals("down")) s.close(); //Closes main socket to terminate the application

J2SE UDP Client The following example shows how we use DatagramSocket to send data to given server's port. Each datagram is independent and may not be delivered String data; //Will be set later, eg. by reading from System.in int port=8000; String server="www.cs.vsb.cz"; try { DatagramSocket s=new DatagramSocket(); DatagramPacket p = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getByName(server), port); s.send(p); s.receive(p); reply=new String(p.getData(),0,p.getLength()); System.out.println("Reply arrived from "+ p.getaddress() +" : "+ p.getport()+" > " + reply); s.close(); catch (IOException e) { System.out.println(e);

J2SE UDP Server We do not have a specific class for datagram servers, since it is not needed. The following example shows how we use DatagramSocket on server's port. try { DatagramSocket s=new DatagramSocket(port); DatagramPacket p; String msg; do { p=new DatagramPacket(new byte[512], 512); // new instance each time due to buffer length s.receive(p); msg = new String(p.getData(),0,p.getLength()); System.out.println("Datagram from " + p.getaddress() + " : " + p.getport() + " > " + msg); p.setdata(msg.touppercase().getbytes()); p.setlength(msg.length()); s.send(p); while (!msg.equals("down")); s.close(); catch (IOException e) { System.out.println(e);

J2ME TCP Socket Connection Establish a socket connection using Connector and read/write data using associated input/output streams. String uri = "socket://" + name + ":" + port; StreamConnection connection = (StreamConnection) Connector.open(uri, Connector.READ_WRITE); InputStream input = connection.openinputstream(); OutputStream output = connection.openoutputstream(); // Send a message. String outgoing =... output.write(outgoing.getbytes()); // Receive a response. byte buffer[] = new byte[size]; int read = input.read(buffer); 13

J2ME TCP Server The Server Socket listens to traffic on given port on localhost. The MIDP implementations differ in handling of the server sockets. MIDP 1.0 the socket is reused for incomming connection StreamConnectionNotifier serversocket = (StreamConnectionNotifier) Connector.open("serversocket://:12345"); StreamConnection conn = serversocket.acceptandopen(); MIDP 2.0 a new socket is created. ServerSocketConnection scn = (ServerSocketConnection) Connector.open("socket://:12345"); SocketConnection sc = (SocketConnection) scn.acceptandopen(); Both the device and the service operator must support servers on mobile devices to make it work (e.g. no private IP addresses!) 14

J2ME Server's Request Handler In order to ensure handling of multiple clients, the request handler is executed by an independent thread of execution. public class EchoRequestHandler extends Thread { public void run() { try { InputStream input = serversocket.getinputstream(); OutputStream output = serversocket.getoutputstream(); int read; byte data[] = new byte[buffer_size]; while ((read = input.read(data))!= -1) { output.write(data, 0, read); output.flush();... 15

UDP Client The following example shows how we use DatagramConnection to send data to given server's port. String data; //Will be set later, eg. by reading from System.in int port=8000; String server="www.cs.vsb.cz"; try { DatagramConnection dc = (DatagramConnection) Connector.open("datagram://" + server + ":" + port); Datagram dg = dc.newdatagram(100); byte[] bytes = message.getbytes(); dc.send(dc.newdatagram(bytes, bytes.length)); dc.receive(dg); if (dg.getlength() > 0) { System.err.println("Message received - " + new String(dg.getData(), 0, dg.getlength())); catch (ConnectionNotFoundException cnfe) { //Connection not successful server is possibly not running, do something about it catch (IOException e) { e.printstacktrace();

UDP Server The following example shows how we use DatagramConnection to to listen on given port. The server changes messages to uppercase. int port=8000; try { DatagramConnection dc = (DatagramConnection)Connector.open("datagram://:" + port); while (true) { Datagram dg = dc.newdatagram(100); dc.receive(dg); address = dg.getaddress(); if (dg.getlength() > 0) { String message = new String(dg.getData(), 0, dg.getlength()).touppercase(); System.err.println("Message received: " + message); byte[] bytes = message.getbytes(); dc.send(dc.newdatagram(bytes, bytes.length)); catch (IOException e) { //Binding not successful another server is possibly running on the same port e.printstacktrace();

Servers Closing Remarks When running servers on mobile devices with J2ME we have to keep in mind following issues: Local socket-based connections between applications may not pose a problem, but the device must be able to run more than one J2ME application/midlet at a time (we do not have to use sockets to communicate between threads). Remote applications must know the IP address of the device acting as server, which may pose a problem (in MIDP 2.0 we can call getlocaladdress() on an opened server socket). To be accessible from Internet, the device must have a public IP address (the addresses containing 10.*.*.*, 172.16.*.* 172.31.*.*, 192.168.*.* and 169.254.*.* are not accessible from Internet, since they are private)

Multi Threading MULTI THREADING 19

Threads There is often need to turn a program into separate, independently running subtasks. Each of these independent subtasks is called a thread, and is programmed as if each thread runs by itself and has the CPU to itself. The thread model is a programming convenience to simplify juggling several operations at the same time within a single program. There is several reasons why to do this. There can be one thread controlling and responding to a GUI, while another thread carries out the tasks or computations requested, while a third thread does file I/O, all for the same program. Some programs are easier to write if they are split into threads. The classic example is the server part of a client/server. When a request comes in from a client, it is very convenient if the server can spawn a new thread to process that one request. 20

Class Thread The simplest way to create a thread is to inherit from class java.lang.thread. The most important method for Thread is run(), which is the code that will be executed simultaneously with the other threads in a program. public class CountDownThread extends Thread { private static int threads = 0; private int thread = threads++; public void run() { for (int i = MAX_COUNT; i > 0; i--) System.out.println("thread #" + thread + ": " + i); Thread thread = new CountDownThread(); thread.start(); 21

Interface Runnable Sometimes it is impossible or inconvenient to inherit from Thread class. The java.lang.runnable interface, declaring the run() method, can be implemented in these cases. public class CountDownThread implements Runnable { private static int threads = 0; private int thread = threads++; public void run() { for (int i = MAX_COUNT; i > 0; i--) System.out.println("thread #" + thread + ": " + i); Thread thread = new Thread(new CountDownThread()); thread.start(); 22

The Life Cycle of a Thread A thread goes through several states during its life cycle: Creating When a thread is created, it is merely an empty object. No system resources are allocated. The thread in this can be only started. Starting The start() method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run() method. Making a Thread Not Runnable A thread becomes Not Runnable when one of these events occurs: its sleep() or wait() method is invoked. Stopping A program does not stop a thread directly. Rather, a thread arranges for its own death by leaving its run() method. 23

Synchronization There are many interesting situations where separate, concurrently running threads do share data and must consider the state and activities of other threads. Java provides a synchronization mechanism based on monitors. Each object in Java has a lock and a monitor to manage the lock. A block marked as synchronized forces any thread wishing to enter the block to acquire corresponding lock first. If another thread already holds the lock, the acquiring thread will block until the lock will be released. The lock is released when the thread leaves the block. public class Game { private Player black, white, previous; public synchronized void turn(player player) { if (player == previous) throw new IllegalPlayerException(...);... 24

Producer-Consumer Problem The producer-consumer problem is a classic synchronization problem. The producer and consumer processes share a common data. The producer executes a loop in which it puts new items into the data and the consumer executes a loop in which it removes items from the data. Producer Consumer SharedData public interface SharedData { public int getsize(); public void put(int[] data); public int[] get(); 25

Producer The producer executes a loop in which it puts new items into the data store. public class Producer extends Thread { private SharedData data; public void run() { for (int i = 0; i < 10; i++) { int[] array = new int[data.getsize()]; System.out.print("put"); for (int j = 0; j < array.length; j++) { array[j] = i; System.out.print(" " + array[j]); System.out.println(); data.put(array);... 26

Consumer The consumer executes a loop in which it removes items from the data store. public class Consumer extends Thread { private SharedData data; public void run() { for (int i = 0; i < 10; i++) { int[] array = data.get(); System.out.print("got"); for (int j = 0; j < array.length; j++) System.out.print(" " + array[j]); System.out.println();... 27

Naïve Shared Data Traditional implementation of the SharedData interface seems to be all right, but... public class NaiveSharedData implements SharedData { private int[] data; public void put(int[] data) { for (int i = 0; i < data.length; i++) this.data[i] = data[i]; public int[] get() { int[] data = new int[this.data.length]; for (int i = 0; i < data.length; i++) data[i] = this.data[i]; return data;... 28

Putting It All Together The producer-consumer problem can be assembled by a few lines of code. SharedData data = new NaiveSharedData(3); Producer producer = new Producer(data); Consumer consumer = new Consumer(data); producer.start(); consumer.start(); Output produced by the program is incorrect, because it contains inconsisten sequence 0 0 1.... put 1 1 1 got 0 0 1 got 1 1 1 put 2 2 2... 29

Acquiring a Lock The code segments within a program that access the same object from separate, concurrent threads are called critical sections. A critical is identified with the synchronized keyword. A lock is associated with every object that has synchronized code. public class BetterSharedData extends NaiveSharedData { public synchronized void put(int[] data) { super.put(data); public synchronized int[] get() { return super.get();... put 2 2 2 got 2 2 2 got 2 2 2 30

Releasing a Lock (1) A thread releases an object's lock when it enters into wait() method of the object. The wait() method causes the thread to wait until another thread invokes the notify() or the notifyall() method for the object. public class PerfectSharedData extends BetterSharedData { private boolean read = true; public synchronized void put(int[] data) { try { while (!read) wait(); super.put(data); read = false; notifyall(); catch (InterruptedException e) {... 31

Releasing a Lock (2) The InterruptedException is thrown by the wait() method if another thread interrupts the current thread. public synchronized int[] get() { int data[] = null; try { while (read) wait(); data = super.get(); read = true; notifyall(); catch (InterruptedException e) { e.printstacktrace(); return data; 32

Scheduling Tasks There are two classes, Timer and TimerTask, to facilitate running of tasks in a background thread. Scheduling one-time tasks Executes a task after specified delay. Scheduling repeating tasks Executes a task at regular intervals. There are two variations for scheduling repeating tasks. Fixed-delay Each execution of a task is based solely on how long it was since the previous task finished. Fixed-rate Each execution of a task is based on when the first task started and the requested delay between tasks. 33

Timer Task A subclass of TimerTask defines what is to be done. It declares abstract method run() which has be implemented by the subclass. public class DrawerTask extends TimerTask { private AnimationCanvas canvas; public DrawerTask(Canvas canvas) { this.canvas = canvas; public void run() { canvas.drawnextframe(); 34

Animation Canvas The drawnextframe() is invoked repeatedly by a DrawerTask. public class AnimationCanvas extends Canvas { private Image[] frames = new Image[FRAMES]; int currentframe = 0; public AnimationCanvas() throws IOException { for (int i = 0; i < frames.length; i++) { frames[i] = Image.createImage("/frame" + (i+1) + ".png"); public void drawnextframe() { currentframe = (currentframe+1)%frames.length; repaint();... 35

Timer The timer executes its task reapeatedly, which in turn affects the animation canvas, forcing it to repaint. AnimationCanvas canvas = new AnimationCanvas(); TimerTask task = new DrawerTask(canvas); Timer timer = new Timer(); // Repeat the task each 1 second. timer.schedule(task, 0, 1000); 36