Socket-based Network Communication in J2SE and J2ME

Size: px
Start display at page:

Download "Socket-based Network Communication in J2SE and J2ME"

Transcription

1 Socket-based Network Communication in J2SE and J2ME 1

2 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

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

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

5 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]]);

6 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 " java.net.urlconnection basic abstract class for URL-based connections. Corresponding sub-class is opened using call to new URL(url).openConnection(); 6

7 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

8 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);

9 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);

10 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

11 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=" 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);

12 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);

13 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

14 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

15 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

16 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=" 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();

17 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();

18 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.*.*.*, *.* *.*, *.* and *.* are not accessible from Internet, since they are private)

19 Multi Threading MULTI THREADING 19

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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 put got got put

30 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 got got

31 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

32 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

33 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

34 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

35 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

36 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

Socket Programming in Java

Socket Programming in Java Socket Programming in Java Learning Objectives The InetAddress Class Using sockets TCP sockets Datagram Sockets Classes in java.net The core package java.net contains a number of classes that allow programmers

More information

Network Communication

Network Communication Network Communication Outline Sockets Datagrams TCP/IP Client-Server model OSI Model Sockets Endpoint for bidirectional communication between two machines. To connect with each other, each of the client

More information

Java Network. Slides prepared by : Farzana Rahman

Java Network. Slides prepared by : Farzana Rahman Java Network Programming 1 Important Java Packages java.net java.io java.rmi java.security java.lang TCP/IP networking I/O streams & utilities Remote Method Invocation Security policies Threading classes

More information

NETWORK PROGRAMMING IN JAVA USING SOCKETS

NETWORK PROGRAMMING IN JAVA USING SOCKETS NETWORK PROGRAMMING IN JAVA USING SOCKETS Prerna Malik, Poonam Rawat Student, Dronacharya College of Engineering, Gurgaon, India Abstract- Network programming refers to writing programs that could be processed

More information

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

Application Development with TCP/IP. Brian S. Mitchell Drexel University Application Development with TCP/IP Brian S. Mitchell Drexel University Agenda TCP/IP Application Development Environment Client/Server Computing with TCP/IP Sockets Port Numbers The TCP/IP Application

More information

Creating a Simple, Multithreaded Chat System with Java

Creating a Simple, Multithreaded Chat System with Java Creating a Simple, Multithreaded Chat System with Java Introduction by George Crawford III In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The program will demonstrate

More information

Network/Socket Programming in Java. Rajkumar Buyya

Network/Socket Programming in Java. Rajkumar Buyya Network/Socket Programming in Java Rajkumar Buyya Elements of C-S Computing a client, a server, and network Client Request Result Network Server Client machine Server machine java.net Used to manage: URL

More information

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

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets Transport layer protocols Interprocess communication Synchronous and asynchronous comm. Message destination Reliability Ordering Client Server Lecture 15: Operating Systems and Networks Behzad Bordbar

More information

Building a Multi-Threaded Web Server

Building a Multi-Threaded Web Server Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous

More information

Network Programming using sockets

Network Programming using sockets Network Programming using sockets TCP/IP layers Layers Message Application Transport Internet Network interface Messages (UDP) or Streams (TCP) UDP or TCP packets IP datagrams Network-specific frames Underlying

More information

Lesson: All About Sockets

Lesson: All About Sockets All About Sockets http://java.sun.com/docs/books/tutorial/networking/sockets/index.html Page 1 sur 1 The Java TM Tutorial Start of Tutorial > Start of Trail Trail: Custom Networking Lesson: All About Sockets

More information

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

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime? CSCI 312 - DATA COMMUNICATIONS AND NETWORKS FALL, 2014 Assignment 4 Working as a group. Working in small gruops of 2-4 students. When you work as a group, you have to return only one home assignment per

More information

Network-based Applications. Pavani Diwanji David Brown JavaSoft

Network-based Applications. Pavani Diwanji David Brown JavaSoft Network-based Applications Pavani Diwanji David Brown JavaSoft Networking in Java Introduction Datagrams, Multicast TCP: Socket, ServerSocket Issues, Gotchas URL, URLConnection Protocol Handlers Q & A

More information

Data Communication & Networks G22.2262-001

Data Communication & Networks G22.2262-001 Data Communication & Networks G22.2262-001 Session 10 - Main Theme Java Sockets Dr. Jean-Claude Franchitti New York University Computer Science Department Courant Institute of Mathematical Sciences 1 Agenda

More information

Division of Informatics, University of Edinburgh

Division of Informatics, University of Edinburgh CS1Bh Lecture Note 20 Client/server computing A modern computing environment consists of not just one computer, but several. When designing such an arrangement of computers it might at first seem that

More information

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

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

More information

Java Programming: Sockets in Java

Java Programming: Sockets in Java Java Programming: Sockets in Java Manuel Oriol May 10, 2007 1 Introduction Network programming is probably one of the features that is most used in the current world. As soon as people want to send or

More information

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

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP CP4044 Lecture 7 1 Networking Learning Outcomes To understand basic network terminology To be able to communicate using Telnet To be aware of some common network services To be able to implement client

More information

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

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets Network Programming Topics in this section include: What a socket is What you can do with a socket The difference between TCP/IP, UDP/IP and Multicast sockets How servers and clients communicate over sockets

More information

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

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus 1. Purpose This assignment exercises how to write a peer-to-peer communicating program using non-blocking

More information

Socket Programming. Announcement. Lectures moved to

Socket Programming. Announcement. Lectures moved to Announcement Lectures moved to 150 GSPP, public policy building, right opposite Cory Hall on Hearst. Effective Jan 31 i.e. next Tuesday Socket Programming Nikhil Shetty GSI, EECS122 Spring 2006 1 Outline

More information

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

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM Socket Programming Rohan Murty Hitesh Ballani Last Modified: 2/8/2004 8:30:45 AM Slides adapted from Prof. Matthews slides from 2003SP Socket programming Goal: learn how to build client/server application

More information

Assignment 4 Solutions

Assignment 4 Solutions CSCI 312 - DATA COMMUNICATIONS AND NETWORKS FALL, 2014 Assignment 4 Solutions Working as a pair Working in pairs. When you work as a pair you have to return only one home assignment per pair on a round.

More information

Sockets Interface Java (C)

Sockets Interface Java (C) Sockets Interface Java (C) Computer Networks Seminar 3 Semestral project (1) Semestral project (2) Project parts: Address plan and VLAN configuration Routing and NAT DNS server DHCP server Securing the

More information

Transparent Redirection of Network Sockets 1

Transparent Redirection of Network Sockets 1 Transparent Redirection of Network Sockets Timothy S. Mitrovich, Kenneth M. Ford, and Niranjan Suri Institute for Human & Machine Cognition University of West Florida {tmitrovi,kford,nsuri@ai.uwf.edu.

More information

SSC - Communication and Networking Java Socket Programming (II)

SSC - Communication and Networking Java Socket Programming (II) SSC - Communication and Networking Java Socket Programming (II) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics Multicast in Java User Datagram

More information

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

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users Programming and Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia http://www.cs.mu.oz.au/~raj

More information

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

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, 4802-4807. Socket Programming Socket Programming Limi Kalita M.Tech Student, Department of Computer Science and Engineering, Assam Down Town University, Guwahati, India. Abstract: The aim of the paper is to introduce sockets, its deployment

More information

Socket programming. Complement for the programming assignment INFO-0010

Socket programming. Complement for the programming assignment INFO-0010 Socket programming Complement for the programming assignment INFO-0010 Outline Socket definition Briefing on the Socket API A simple example in Java Multi-threading and Synchronization HTTP protocol Debugging

More information

Threads & Tasks: Executor Framework

Threads & Tasks: Executor Framework Threads & Tasks: Executor Framework Introduction & Motivation WebServer Executor Framework Callable and Future 12 April 2012 1 Threads & Tasks Motivations for using threads Actor-based Goal: Create an

More information

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

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers DNS: Domain Name System DNS: Domain Names People: many identifiers: SSN, name, Passport # Internet hosts, routers: Always: IP address (32 bit) - used for addressing datagrams Often: name, e.g., nifc14.wsu.edu

More information

Mail User Agent Project

Mail User Agent Project Mail User Agent Project Tom Kelliher, CS 325 100 points, due May 4, 2011 Introduction (From Kurose & Ross, 4th ed.) In this project you will implement a mail user agent (MUA) that sends mail to other users.

More information

JAVA Program For Processing SMS Messages

JAVA Program For Processing SMS Messages JAVA Program For Processing SMS Messages Krishna Akkulu The paper describes the Java program implemented for the MultiModem GPRS wireless modem. The MultiModem offers standards-based quad-band GSM/GPRS

More information

Communicating with a Barco projector over network. Technical note

Communicating with a Barco projector over network. Technical note Communicating with a Barco projector over network Technical note MED20080612/00 12/06/2008 Barco nv Media & Entertainment Division Noordlaan 5, B-8520 Kuurne Phone: +32 56.36.89.70 Fax: +32 56.36.883.86

More information

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

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1 Introduction to Java Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233 ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1 What Is a Socket? A socket is one end-point of a two-way

More information

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

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Transparent Redirection of Network Sockets 1

Transparent Redirection of Network Sockets 1 Transparent Redirection of Network Sockets 1 Timothy S. Mitrovich, Kenneth M. Ford, and Niranjan Suri Institute for Human & Machine Cognition University of West Florida {tmitrovi,kford,nsuri}@ai.uwf.edu

More information

An Android-based Instant Message Application

An Android-based Instant Message Application An Android-based Instant Message Application Qi Lai, Mao Zheng and Tom Gendreau Department of Computer Science University of Wisconsin - La Crosse La Crosse, WI 54601 mzheng@uwlax.edu Abstract One of the

More information

Multithreaded Programming

Multithreaded Programming Java Multithreaded Programming This chapter presents multithreading, which is one of the core features supported by Java. The chapter introduces the need for expressing concurrency to support simultaneous

More information

An Overview of Java. overview-1

An Overview of Java. overview-1 An Overview of Java overview-1 Contents What is Java Major Java features Java virtual machine Java programming language Java class libraries (API) GUI Support in Java Networking and Threads in Java overview-2

More information

Operating Systems Design 16. Networking: Sockets

Operating Systems Design 16. Networking: Sockets Operating Systems Design 16. Networking: Sockets Paul Krzyzanowski pxk@cs.rutgers.edu 1 Sockets IP lets us send data between machines TCP & UDP are transport layer protocols Contain port number to identify

More information

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

Lecture 2-ter. 2. A communication example Managing a HTTP v1.0 connection. G.Bianchi, G.Neglia, V.Mancuso Lecture 2-ter. 2 A communication example Managing a HTTP v1.0 connection Managing a HTTP request User digits URL and press return (or clicks ). What happens (HTTP 1.0): 1. Browser opens a TCP transport

More information

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

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

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

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket. 164 CHAPTER 2 APPLICATION LAYER connection requests, as done in TCPServer.java. If multiple clients access this application, they will all send their packets into this single door, serversocket. String

More information

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amulti threaded programming language which means we can develop multi threaded program

More information

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

TP1 : Correction. Rappels : Stream, Thread et Socket TCP Université Paris 7 M1 II Protocoles réseaux TP1 : Correction Rappels : Stream, Thread et Socket TCP Tous les programmes seront écrits en Java. 1. (a) Ecrire une application qui lit des chaines au clavier

More information

CS11 Java. Fall 2014-2015 Lecture 7

CS11 Java. Fall 2014-2015 Lecture 7 CS11 Java Fall 2014-2015 Lecture 7 Today s Topics! All about Java Threads! Some Lab 7 tips Java Threading Recap! A program can use multiple threads to do several things at once " A thread can have local

More information

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

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version Version 3.5 JEFFERSON LAB Data Acquisition Group cmsg Developer s Guide J E F F E R S O N L A B D A T A A C Q U I S I T I O N G R O U P cmsg Developer s Guide Elliott Wolin wolin@jlab.org Carl Timmer timmer@jlab.org

More information

INPUT AND OUTPUT STREAMS

INPUT AND OUTPUT STREAMS INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,

More information

TCP/IP - Socket Programming

TCP/IP - Socket Programming TCP/IP - Socket Programming jrb@socket.to.me Jim Binkley 1 sockets - overview sockets simple client - server model look at tcpclient/tcpserver.c look at udpclient/udpserver.c tcp/udp contrasts normal master/slave

More information

Outline of this lecture G52CON: Concepts of Concurrency

Outline of this lecture G52CON: Concepts of Concurrency Outline of this lecture G52CON: Concepts of Concurrency Lecture 10 Synchronisation in Java Natasha Alechina School of Computer Science nza@cs.nott.ac.uk mutual exclusion in Java condition synchronisation

More information

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

Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute Network programming in Java using Socket Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute Abstract This paper describes about Network programming

More information

Building a Java chat server

Building a Java chat server Building a Java chat server Presented by developerworks, your source for great tutorials Table of Contents If you're viewing this document online, you can click any of the topics below to link directly

More information

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

CISC 4700 L01 Network & Client- Server Programming Spring 2016. Harold, Chapter 8: Sockets for Clients CISC 4700 L01 Network & Client- Server Programming Spring 2016 Harold, Chapter 8: Sockets for Clients Datagram: Internet data packet Header: accounting info (e.g., address, port of source and dest) Payload:

More information

Chapter 3. Internet Applications and Network Programming

Chapter 3. Internet Applications and Network Programming Chapter 3 Internet Applications and Network Programming 1 Introduction The Internet offers users a rich diversity of services none of the services is part of the underlying communication infrastructure

More information

Transport Layer Protocols

Transport Layer Protocols Transport Layer Protocols Version. Transport layer performs two main tasks for the application layer by using the network layer. It provides end to end communication between two applications, and implements

More information

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE 50-20-44 DATA COMMUNICATIONS MANAGEMENT NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE John P. Slone INSIDE Java s Target Environment, Networking Basics, Java Networking Primitives, Connection-Oriented

More information

Network Programming. Writing network and internet applications.

Network Programming. Writing network and internet applications. Network Programming Writing network and internet applications. Overview > Network programming basics > Sockets > The TCP Server Framework > The Reactor Framework > High Level Protocols: HTTP, FTP and E-Mail

More information

Application of Design for Verification with Concurrency Controllers to Air Traffic Control Software

Application of Design for Verification with Concurrency Controllers to Air Traffic Control Software Application of Design for Verification with Concurrency Controllers to Air Traffic Control Software Aysu Betin-Can Tevfik Bultan Computer Science Department University of California Santa Barbara, CA 93106,

More information

Intranet, Extranet, Firewall

Intranet, Extranet, Firewall Indian Institute of Technology Kharagpur Intranet, Extranet, Firewall Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 31: Intranet, Extranet, Firewall On completion,

More information

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.

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. Session Layer The session layer resides above the transport layer, and provides value added services to the underlying transport layer services. The session layer (along with the presentation layer) add

More information

Manual. Programmer's Guide for Java API

Manual. Programmer's Guide for Java API 2013-02-01 1 (15) Programmer's Guide for Java API Description This document describes how to develop Content Gateway services with Java API. TS1209243890 1.0 Company information TeliaSonera Finland Oyj

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling

More information

What is an I/O Stream?

What is an I/O Stream? Java I/O Stream 1 Topics What is an I/O stream? Types of Streams Stream class hierarchy Control flow of an I/O operation using Streams Byte streams Character streams Buffered streams Standard I/O streams

More information

Logging in Java Applications

Logging in Java Applications Logging in Java Applications Logging provides a way to capture information about the operation of an application. Once captured, the information can be used for many purposes, but it is particularly useful

More information

Interprocess Communication Message Passing

Interprocess Communication Message Passing Interprocess Communication Message Passing IPC facility provides two operations: send(message) message size fixed or variable receive(message) If P and Q wish to communicate, they need to: establish a

More information

Java Concurrency Framework. Sidartha Gracias

Java Concurrency Framework. Sidartha Gracias Java Concurrency Framework Sidartha Gracias Executive Summary This is a beginners introduction to the java concurrency framework Some familiarity with concurrent programs is assumed However the presentation

More information

Socket Programming in C/C++

Socket Programming in C/C++ September 24, 2004 Contact Info Mani Radhakrishnan Office 4224 SEL email mradhakr @ cs. uic. edu Office Hours Tuesday 1-4 PM Introduction Sockets are a protocol independent method of creating a connection

More information

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

Socket Programming. A er learning the contents of this chapter, the reader will be able to: Java Socket Programming This chapter presents key concepts of intercommunication between programs running on different computers in the network. It introduces elements of network programming and concepts

More information

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

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software Session NM059 TCP/IP Programming on VMS Geoff Bryant Process Software Course Roadmap Slide 160 NM055 (11:00-12:00) Important Terms and Concepts TCP/IP and Client/Server Model Sockets and TLI Client/Server

More information

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab. angelo.liguori@uniroma3.it

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab. angelo.liguori@uniroma3.it Course: Software Defined Radio ICT SEcurity BASICS Angelo Liguori angelo.liguori@uniroma3.it SP4TE lab 1 Simple Timing Covert Channel Unintended information about data gets leaked through observing the

More information

Files and input/output streams

Files and input/output streams Unit 9 Files and input/output streams Summary The concept of file Writing and reading text files Operations on files Input streams: keyboard, file, internet Output streams: file, video Generalized writing

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

Mutual Exclusion using Monitors

Mutual Exclusion using Monitors Mutual Exclusion using Monitors Some programming languages, such as Concurrent Pascal, Modula-2 and Java provide mutual exclusion facilities called monitors. They are similar to modules in languages that

More information

Implementing Network Software

Implementing Network Software Implementing Network Software Outline Sockets Example Process Models Message Buffers Spring 2007 CSE 30264 1 Sockets Application Programming Interface (API) Socket interface socket : point where an application

More information

Chapter 8 Implementing FSP Models in Java

Chapter 8 Implementing FSP Models in Java Chapter 8 Implementing FSP Models in Java 1 8.1.1: The Carpark Model A controller is required for a carpark, which only permits cars to enter when the carpark is not full and does not permit cars to leave

More information

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

Note! The problem set consists of two parts: Part I: The problem specifications pages Part II: The answer pages Part I: The problem specifications NTNU The Norwegian University of Science and Technology Department of Telematics Note! The problem set consists of two parts: Part I: The problem specifications pages

More information

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

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input

More information

Chapter 6 Concurrent Programming

Chapter 6 Concurrent Programming Chapter 6 Concurrent Programming Outline 6.1 Introduction 6.2 Monitors 6.2.1 Condition Variables 6.2.2 Simple Resource Allocation with Monitors 6.2.3 Monitor Example: Circular Buffer 6.2.4 Monitor Example:

More information

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

!# $ %!&' # &! ())*!$ !"# $ %!&' # &! ())*!$ !" #!$ %& ' ( ) * +,--!&"" $.!! /+010!" +!, 31! 4)&/0! $ #"5!! & + 6+ " 5 0 7 /&8-9%& ( +" 5)& /*#.! &( $ 1(" 5 # ( 8 +1 + # + 7$ (+!98 +&%& ( +!" (!+!/ (!-. 5 7 (! 7 1+1( & + ":!

More information

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

Threads 1. When writing games you need to do more than one thing at once. Threads 1 Threads Slide 1 When writing games you need to do more than one thing at once. Threads offer a way of automatically allowing more than one thing to happen at the same time. Java has threads as

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

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

Domain Name System (DNS) Omer F. Rana. Networks and Data Communications 1 Domain Name System (DNS) Omer F. Rana Networks and Data Communications 1 What is a DNS Each institution on the internet has a host that runs a process called a Domain Name Server (also DNS!) It is not

More information

AVRO - SERIALIZATION

AVRO - SERIALIZATION http://www.tutorialspoint.com/avro/avro_serialization.htm AVRO - SERIALIZATION Copyright tutorialspoint.com What is Serialization? Serialization is the process of translating data structures or objects

More information

WRITING DATA TO A BINARY FILE

WRITING DATA TO A BINARY FILE WRITING DATA TO A BINARY FILE TEXT FILES VS. BINARY FILES Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters.

More information

PRODUCTIVITY ESTIMATION OF UNIX OPERATING SYSTEM

PRODUCTIVITY ESTIMATION OF UNIX OPERATING SYSTEM Computer Modelling & New Technologies, 2002, Volume 6, No.1, 62-68 Transport and Telecommunication Institute, Lomonosov Str.1, Riga, LV-1019, Latvia STATISTICS AND RELIABILITY PRODUCTIVITY ESTIMATION OF

More information

JAVA - FILES AND I/O

JAVA - FILES AND I/O http://www.tutorialspoint.com/java/java_files_io.htm JAVA - FILES AND I/O Copyright tutorialspoint.com The java.io package contains nearly every class you might ever need to perform input and output I/O

More information

Java Memory Model: Content

Java Memory Model: Content Java Memory Model: Content Memory Models Double Checked Locking Problem Java Memory Model: Happens Before Relation Volatile: in depth 16 March 2012 1 Java Memory Model JMM specifies guarantees given by

More information

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

Disfer. Sink - Sensor Connectivity and Sensor Android Application. Protocol implementation: Charilaos Stais (stais AT aueb.gr) Disfer Sink - Sensor Connectivity and Sensor Android Application Protocol implementation: Charilaos Stais (stais AT aueb.gr) Android development: Dimitri Balerinas (dimi.balerinas AT gmail.com) Supervised

More information

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

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS. Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 Name: SOLUTIONS Athena* User Name: Instructions This quiz is 50 minutes long. It contains

More information

Event-Driven Programming

Event-Driven Programming Event-Driven Programming Lecture 4 Jenny Walter Fall 2008 Simple Graphics Program import acm.graphics.*; import java.awt.*; import acm.program.*; public class Circle extends GraphicsProgram { public void

More information

OBJECT ORIENTED PROGRAMMING LANGUAGE

OBJECT ORIENTED PROGRAMMING LANGUAGE UNIT-6 (MULTI THREADING) Multi Threading: Java Language Classes The java.lang package contains the collection of base types (language types) that are always imported into any given compilation unit. This

More information

Remote Method Invocation

Remote Method Invocation Remote Method Invocation The network is the computer Consider the following program organization: method call SomeClass AnotherClass returned object computer 1 computer 2 If the network is the computer,

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

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

Java Programming Unit 10. Stock Price Quotes with URL, Sockets, and RMI Java Programming Unit 10 Stock Price Quotes with URL, Sockets, and RMI GeFng Stock Quotes From Yahoo! 1. Visit hjp://finance.yahoo.com, enter AAPL - the symbol of the Apple s stock, and press the bujon

More information

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

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture Last Class: OS and Computer Architecture System bus Network card CPU, memory, I/O devices, network card, system bus Lecture 3, page 1 Last Class: OS and Computer Architecture OS Service Protection Interrupts

More information

Monitors, Java, Threads and Processes

Monitors, Java, Threads and Processes Monitors, Java, Threads and Processes 185 An object-oriented view of shared memory A semaphore can be seen as a shared object accessible through two methods: wait and signal. The idea behind the concept

More information

Socket Programming. Srinidhi Varadarajan

Socket Programming. Srinidhi Varadarajan Socket Programming Srinidhi Varadarajan Client-server paradigm Client: initiates contact with server ( speaks first ) typically requests service from server, for Web, client is implemented in browser;

More information

Java from a C perspective. Plan

Java from a C perspective. Plan Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,

More information