Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.

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.
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Java Sockets Source:
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
Moshe Fresko Bar-Ilan University
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
1 TCP socket application Architecture of Client-Server Applications Java Socket Programming Client Application Server Application.
Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.
System Programming Practical session 10 Java sockets.
Java sockets. From waiting.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
1 Socket-based Client- Server Application Client-Server application architecture Choosing services – Connectionless atau Connection-oriented.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Networking Basics Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram.
Practical Session 11 Multi Client-Server Java NIO.
Ryerson University CPS Distributing Computing with Java.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
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.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
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.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Java Sockets Brad Vander Zanden. Agenda What are sockets Client/Server interaction Single client/server example Synchronized data objects Multi-threaded.
VII. Sockets. 1. What is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes.
CSC 480 Software Engineering Socket. What is Socket? A socket is one end-point of a two-way communication link between two programs running on the network.
Practical Session 11 Multi Client-Server Java NIO.
Servers and Sockets Carol Wolf Computer Science. Java network programming classes  SocketImpl – abstract class and superclass of the rest  Four fields:
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Peter Lee April 8, 2004.
Java Server Programming Web Interface for Java Programs.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
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.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
CSC 480 Software Engineering Lab 2 – Multi-Threading Oct 18, 2002.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
1 Socket-based Client- Server Application Client-Server application architecture Choosing services – Connectionless atau Connection-oriented.
第十一讲 分布式编程 Socket and RMI 李庆旭. 2 本章内容提要  Socket TCP /IP protocol suit Socket A TCP Server and a TCP Client Supporting Multiple Concurrent Clients A UDP.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Multithreaded/Sockets/Server Welcome.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Java 13. Networking public class SumTest {
Echo Networking COMP
Threads in Java Two ways to start a thread
Source: Java Sockets Source:
Thread Pools (Worker Queues) cs
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Thread Pools (Worker Queues) cs
Block 15 Developing the Calculator application
Socket-based Client-Server Application
CS1101: Programming Methodology Recitation 7 – Exceptions
Client-server Programming
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
„Networking”.
Implementação de Socket UDP e TCP em Java
Socket-based Client-Server Application
Distributed Computing
CS18000: Problem Solving and Object-Oriented Programming
Presentation transcript:

Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns Socket object. Client Socket used for I/O

import java.net.*; import java.io.*; public class KnockKnockServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); }

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }}

import java.io.*; import java.net.*; public class KnockKnockClient { public static void main(String[] args) throws IOException { Socket kkSocket = null; PrintWriter out = null; BufferedReader in = null; try { kkSocket = new Socket("taranis", 4444); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: taranis."); System.exit(1); }

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } } out.close(); in.close(); stdIn.close(); kkSocket.close(); }}

import java.net.*; import java.io.*; public class KnockKnockProtocol { private static final int WAITING = 0; private static final int SENTKNOCKKNOCK = 1; private static final int SENTCLUE = 2; private static final int ANOTHER = 3; private static final int NUMJOKES = 5; private int state = WAITING; private int currentJoke = 0; private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" }; private String[] answers = { "Turnip the heat, it's cold in here!", "I didn't know you could yodel!", "Bless you!", "Is there an owl in here?", "Is there an echo in here?" };

public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "Knock! Knock!"; state = SENTKNOCKKNOCK; } else if (state == SENTKNOCKKNOCK) { if (theInput.equalsIgnoreCase("Who's there?")) { theOutput = clues[currentJoke]; state = SENTCLUE; } else { theOutput = "You're supposed to say \"Who's there?\"! " + "Try again. Knock! Knock!"; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) { theOutput = answers[currentJoke] + " Want another? (y/n)"; state = ANOTHER; } else { theOutput = "You're supposed to say \"" + clues[currentJoke] + " who?\"" + "! Try again. Knock! Knock!"; state = SENTKNOCKKNOCK; }

} else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Knock! Knock!"; if (currentJoke == (NUMJOKES - 1)) currentJoke = 0; else currentJoke++; state = SENTKNOCKKNOCK; } else { theOutput = "Bye."; state = WAITING; } } return theOutput; }}

Multiple-Clients One thread per client connection on the server Modification of Knock-Knock Server to handle multiple clients Logic: Server loops accepting connections and creating new threads to deal with each client

Thread Pools Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed. Internally the tasks are inserted into a BlockingQueue which the threads in the pool are dequeuing from. When a new task is inserted into the queue one of the idle threads will dequeue it successfully and execute it. The rest of the idle threads in the pool will be blocked waiting to dequeue tasks.

Thread pools are often used in multi threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently. Java 5 comes with built in thread pools in the java.util.concurrent package, so you don't have to implement your own thread pool.

public class ThreadPool { private BlockingQueue taskQueue = null; private List threads = new ArrayList (); private boolean isStopped = false; public ThreadPool(int noOfThreads, int maxNoOfTasks){ taskQueue = new BlockingQueue(maxNoOfTasks); for(int i=0; i<noOfThreads; i++){ threads.add(new PoolThread(taskQueue)); } for(PoolThread thread : threads){ thread.start(); } public void synchronized execute(Runnable task){ if(this.isStopped) throw new IllegalStateException("ThreadPool is stopped"); this.taskQueue.enqueue(task); } public synchronized void stop(){ this.isStopped = true; for(PoolThread thread : threads){ thread.stop(); }

public class PoolThread extends Thread { private BlockingQueue taskQueue = null; private boolean isStopped = false; public PoolThread(BlockingQueue queue){ taskQueue = queue; } public void run(){ while(!isStopped()){ try{ Runnable runnable = (Runnable) taskQueue.dequeue(); runnable.run(); } catch(Exception e){ //log or otherwise report exception, //but keep pool thread alive. } public synchronized void stop(){ isStopped = true; this.interrupt(); //break pool thread out of dequeue() call. } public synchronized void isStopped(){ return isStopped; }

while(! isStopped()){ Socket clientSocket = null; try { clientSocket = this.serverSocket.accept(); } catch (IOException e) { if(isStopped()) { System.out.println("Server Stopped.") ; return; } throw new RuntimeException( "Error accepting client connection", e); } this.threadPool.execute( new WorkerRunnable(clientSocket, "Thread Pooled Server")); }