Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.

Slides:



Advertisements
Similar presentations
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Advertisements

Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
Basic Socket Programming with Java. What is a socket?  Generally refers to a stream connecting processes running in different address spaces (across.
Socket Programming.
1 Java Networking – Part I CS , Spring 2008/9.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
Client/Server In Java An Introduction to TCP/IP and Sockets.
Networking with Java CSc 335 Object-Oriented Programming and Design Spring 2009.
Fundamentals of Python: From First Programs Through Data Structures
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
TCP Sockets Reliable Communication. TCP As mentioned before, TCP sits on top of other layers (IP, hardware) and implements Reliability In-order delivery.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
Greg Jernegan Brandon Simmons. The Beginning…  The problem Huge demand for internet enabled applications and programs that communicate over a network.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Sockets Sockets A socket is an object that encapsulates a TCP/IP connection There is a socket on both ends of a connection, the client side and the server.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Networking A network represents interconnection of computers that is capable.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Networking Code CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Li Tak Sing COMPS311F. Case study: a multithreaded chat server The source contains 3 files: ChatServer //the chat server ChatThread //the thread on the.
SOCKET PROGRAMMING WITH JAVA By Collin Donaldson.
1 Network Communications A Brief Introduction. 2 Network Communications.
Advance Computer Programming Networking Basics – explores the java.net package which provides support for networking. – Also Called “programming for the.
Network Programming. These days almost all devices.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Object-Orientated Analysis, Design and Programming
Threads in Java Two ways to start a thread
Lecture 21 Sockets 1 (Not in D&D) Date.
NETWORK PROGRAMMING CNET 441
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Multiplexing/Demux.
Clients and Servers 19-Jul-19.
CS18000: Problem Solving and Object-Oriented Programming
Clients and Servers 13-Sep-19.
Exceptions and networking
Presentation transcript:

Li Tak Sing COMPS311F

Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate integers randomly at random intervals. The integers will then be put into the buffer. A number of consumers which get integers from the buffer at random intervals.

File location The application can be accessed at: 0/build/classes/CP.html The source file can be obtained at: 0/src/CP.java

Colour coding black: The thread is trying to lock the buffer blue: The thread has release the lock because it cannot process. green: The thread is sleeping. red: The thread has finished the current task. orange: The thread has acquired the lock of the buffer.

Attributes private int size = 3; private Producer[] p; private Consumer[] c; private javax.swing.JButton stack[] = new javax.swing.JButton[size]; private int no = 0;

The put method private synchronized void put(int i, Producer p) { p.setStatus("locking " + i); try {Thread.sleep(1000);} catch (Exception e) {}; while (no == size) { try { p.setStatus("waiting to put " + i); wait(); } catch (Exception e) { } notifyAll(); stack[size-(++no)].setText(Integer.toString(i)); p.setStatus("put "+i); try {Thread.sleep(1000);} catch (Exception e) {}; }

The get method private synchronized int get(Consumer p) { p.setStatus("locking"); try {Thread.sleep(1000);} catch (Exception e) {}; while (no == 0) { try { p.setStatus("waiting to get "); wait(); } catch (Exception e) { } notifyAll();

The get method int i = 0; try { i = Integer.parseInt(stack[size-(no)].getText()); stack[size-no].setText(""); no--; } catch (Exception e) { } notifyAll(); p.setStatus("got "+i); try {Thread.sleep(1000);} catch (Exception e) {}; return i; }

CPButton This is the class of both Producer and Consumer. It is a JButton and has implemented the Runnable interface.

Producer public void run() { while (true) { try { int number = (int) (Math.random() * 10); setStatus("putting "+number); put(number,this); int interval = ((int) (Math.random() * 10000)); this.setStatus("sleeping "+(interval/1000)+"secs"); Thread.sleep(interval); } catch (Exception e) { }

Consumer public void run() { while (true) { try { setStatus("getting"); int number=get(this); int interval = ((int) (Math.random() * 10000)); this.setStatus("sleeping "+(interval/1000)+"secs"); Thread.sleep(interval); } catch (Exception e) { }

Networking There are two modes: connection oriented and connectionless. The connection oriented mode works like telephone lines. Before you can talk to another person over the phone, you need to establish a circuit connecting you and the other person. Then, you can use this circuit to transmit voice signal. The signal will always arrive in the same order as they are sent.

Connectionless mode The connectionless mode works like the post office. When you send a letter to another person, the post office will deliver the letter to that person. However, if you send many letters to the same person, there is no guarantee that the letter will arrive at the same order as they are sent.

IP address and Port Before we can communicate with a computer, we need to know how to locate that computer first. Computers are identified by its IP address in the internet. An IP address consists of four bytes and are usually expressed in the form of: xxx.xxx.xxx.xxx Since IP address is difficult to remember, we usually use host name instead.

Host name and domain name server Note that IP addresses and host names do not form a one to one relation. An IP address can map to zero, one or even more host names. Similarly, a host name can also map to zero, one or even more IP addresses.

port A computer can have many services. For example, a server would usually provide services like http, ftp, telnet etc. So when you want to talk to a computer, you need to specify which service you want to use. This is done by specifying the port number corresponding to the service.

port A port number is a 2 bytes integers starting from 1. Some common services use pre-defined port: ftp: 21, telnet: 23, http: 80 etc. So when two computers are connected using the connection oriented mode, the connection is identified uniquely by the ip addresses and the ports used by the two computer.

IP: IP: port 3334 port 234 A connection is uniquely identified by the IP addresses and port numbers at the two ends.

Server The ip address and port number work like a telephone with some extension. So you want to be a server, it is similar to one who is wait for others to call. So the first thing he/she needs to do is to let others to know the telephone number and the extension number.

Server However, when other people want to talk to the server, there is no need to use a particular telephone and extension. You can use any one that is available.

Server If the server is a multithreaded server, then the server can be talking to a number of clients at a time.

IP: IP: port 3334 port 234 A connection is uniquely identified by the IP addresses and port numbers at the two ends. IP: port 8242

Server So, even though a server is waiting for requests at one port only, it is possible for it to entertain many requests at the same time.

Socket Socket is the term used to describe one end of a connection. So to create a connection between two computers, you first need to have two sockets at the two ends.

Sockets There are two kinds of sockets, one on the server and one on the client. As mentioned earlier, when you need to specify the port to be used on the server side. In Java, ServerSocket is used to model sockets on the server side.

ServerSocket the constructor public ServerSocket(int port) throws IOException can be used to create a socket on the server side with the given port. The constructor will throw IOException if there is a problem in creating the server socket.

Socket After the ServerSocket is created, then we can make the server listen to the port by invoking the accept method of ServerSocket: ServerSocket sSocket=new ServerSocket(4444); Socket socket=sSocket.accept(); When the accept method is invoked, the thread is blocked until there is a request from a client for this service.

Socket Then, a Socket will be returned. As said earlier, a socket is one end of a network connection. To start the communication, you need to get an input stream and an output stream by using the method: InputStream getInputStream() throws IOException OutputStream getOutputStream() throws IOException

A single threaded server So a single threaded server would do something like this: ServerSocket sSocket=new ServerSocket(11111); while (true) { Socket socket=sSocket.accept(); OutputStream outputStream=socket.getOutputStream(); InputStream inputStream=socket.getInputStream();.... // we can do something about the input and output. }

The client On the client side, there is no need to create a ServerSocket. Instead, we would use a constructor of Socket: public Socket(String host, int port) throws UnknownHostException, IOException Note that we need to specify the host and the port number here. To specify the host, you can either use the IP address or the host name.

localhost If you have two computers, you can use one computer as the server and the other as the client to test your network program. However, if you only has one computer, how can you test a network program? You can do that by using the loopback address: which refers to your computer.

A simple server Let's write a simple single threaded server which accepts two integers from a client and then returns the sum of the two integers to the client.

public class MyServer { static public void main(String st[]) { try { java.net.ServerSocket sSocket=new java.net.ServerSocket(11111); while (true) { java.net.Socket socket=sSocket.accept(); java.io.OutputStream output=socket.getOutputStream(); java.io.InputStream input=socket.getInputStream(); java.io.DataOutputStream dout=new java.io.DataOutputStream(output); java.io.DataInputStream din=new java.io.DataInputStream(input); int a1=din.readInt();

int a2=din.readInt(); dout.writeInt(a1+a2); dout.close(); din.close(); socket.close(); } catch (Exception e) { }

public class MyClient { public static void main(String st[]) { try { java.net.Socket socket=new java.net.Socket(" ",11111); java.io.OutputStream output=socket.getOutputStream(); java.io.InputStream input=socket.getInputStream(); java.io.DataOutputStream dout=new java.io.DataOutputStream(output); java.io.DataInputStream din=new java.io.DataInputStream(input); dout.writeInt(3); dout.writeInt(4); int result=din.readInt(); System.out.println("the result is "+result); } catch (Exception e) { }

A multithreaded server The previous server can only handle one request at a time. This does not seem to be a problem as each request does not last for too long. However, if a server needs to provide some computationally intensive service, there is a need to have a multithreaded server or else a client may have to wait for a long time before it is served.

Multithreaded server In a multithreaded server, when there is an incoming request, we would create a thread to handle the request. Now, lets rewrite the last simple server to be a multithreaded server.

Multithreaded server First we create a class MyThread which is used to handle a request. In our design, the constructor of MyThread has a parameter of type Socket which is the socket returned from the accept method of ServerSocket. Then the run method of MyThread would perform the necessary operations.

public class MyThread extends Thread { private java.net.Socket socket; /** Creates a new instance of MyThread */ public MyThread(java.net.Socket socket) { this.socket=socket; } public void run() { try { java.io.OutputStream output=socket.getOutputStream(); java.io.InputStream input=socket.getInputStream(); java.io.DataOutputStream dout=new java.io.DataOutputStream(output);

java.io.DataInputStream din=new java.io.DataInputStream(input); int a1=din.readInt(); int a2=din.readInt(); dout.writeInt(a1+a2); dout.close(); din.close(); socket.close(); } catch (Exception e) {} } }

public class MultiThreadedServer { static public void main(String st[]) { try { java.net.ServerSocket sSocket=new java.net.ServerSocket(11111); while (true) { java.net.Socket socket=sSocket.accept(); MyThread thread=new MyThread(socket); thread.start(); } catch (Exception e) { }