1 / 24

Socket Programing

Socket Programing. Read Chapters 2 & 3 in Graba. Socket To Me!!. Server Sockets. Step 1. Listen for a client connection on specified port. ServerSocket serverSocket = new ServerSocket(PORT_NUM);. Step 2. Wait and listen for client. Socket link = serverSocket.accept( );.

Download Presentation

Socket Programing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Socket Programing Read Chapters 2 & 3 in Graba Socket To Me!!

  2. Server Sockets Step 1. Listen for a client connection on specified port ServerSocket serverSocket = new ServerSocket(PORT_NUM); Step 2. Wait and listen for client Socket link = serverSocket.accept( ); Step 3. Set-up input and output streams Scanner input = new Scanner(link.getInputStream( ) ); PrintWriter output = new PrintWriter(link.getOutputStream( ) , true); Step 4. Send and receive data output.println(“Waiting to hear from you…”); String message = input.nextLine( ); Step 5. Close the connection to the client when done link.close( );

  3. Details about Server Sockets ServerSocket uses the Internet transport protocol TCP to establish a virtual channel between the Server and a client. The channel is “reliable” and is maintained for the duration of the session. It MUST be closed upon termination of a session.. What is a port? A port is a “label” for identifying a process on a particular host. Each TCP packet contains a pair of 16-bit fields for the source and destination port addresses. This means that there may be as many as 65536 addressable processes on each host. The first 1024 addresses are reserved for well-known applications such as http. A programmer may select any other address for his/her own application.

  4. TCP/IP Application Model Application TCP UDP IP Network Protocols Protocol Stack

  5. TCP a Reliable Byte Stream Protocol TCP (Transport Control Protocol) is a connection oriented protocol that guarantees the reliable, in-order delivery of a stream of bytes. • TCP is full-duplex (it supports a pair of byte streams flowing in opposite directions.) • It provides for flow control which allows a receiver to limit the rate at which a sender can transmit. • It implements a congestion control mechanism which throttles the sender from overloading the network. • Like UDP, it provides for multiplexing/demultiplexing of packets

  6. TCP Packet Format For reliable, in order delivery For flow control For process demultiplexing Other fields Destination Port Source Port Sequence Number (byte count) Acknowledgement 0 Flags Advertised Window HdrLen Checksum Urgent Pointer Options (variable length) Data

  7. Port: An abstraction for locating services Each service is associated with a given port number on a given machine. When you ask for a particular port, you are requesting the service associated with that port number. There are 2 ** 16 available numbers, but the numbers 1 – 1024 are reserved for “well-known” services and should not be used for user initiated services. Port number 7 is used for the echo server and Port number 13 is used for the time and date service It is up to the client to know which port number the desired service is running on.

  8. Locating Resources While TCP provides a reliable virtual channel between two application processes, the actual delivery service over the Internet is provided by IP. To locate a resource on the Internet, you must know both the IP address of the host machine and the port at which the application process is “listening”. The URL is another means of locating a resource. It can be used to find the IP address of the host within which it resides.

  9. Locating Resources import java.net.*; //for class InetAddress import java.util.*; //for Scanner public class IPFinder { public static void main(String[] args) { String host; Scanner input = new Scanner(System.in); System.out.print (“\nEnter the URL of the host: “); host = input.next( ); try { InetAddress address = InetAddress.getByName(host); System.out.println(“IP address of “ + host + “ is: “ + address.toString( )); InetAddress localhost = InetAddress.getLocalHost( ); System.out.println(“Local IP address is: “ + localhost); } catch (UnknownHostException uhx) { System.out.println(“Could not locate host” ); } } }

  10. Handling Multiple Simultaneous Clients A Server must be capable of handling multiple client requests New clients will be run on their own individual thread

  11. Example: TCP Server Socket – code fragment Listen to a port for a socket trying to connect Return the connecting socket Create a new thread to handle the connection and continue to listen for additional requests Close the Server Socket if exception is raised try { theServer = new ServerSocket(echoPort); try{ while(true) { Socket theConnection = theServer.accept(); System.out.println("Connection established with " + theConnection); Responder theResponder = new Responder(theConnection); Thread t1 = new Thread(theResponder); t1.start(); } } catch (IOException e) { theServer.close(); System.err.println(e); } } catch(IOException e) { System.err.println(e); }

  12. Start a new thread with a new socket to serve client class Responder implements Runnable { Scanner iStream; PrintWriter pStream; Socket theConnection; public Responder(Socket theSocket) { theConnection = theSocket; try { iStream = new Scanner(theConnection.getInputStream())); pStream = new PrintWriter(theConnection.getOutputStream()); } catch(IOException ignore){}; } Continued on next slide

  13. public void run() { String theLine; try{ while(true) { theLine = iStream.readLine(); System.out.println(theLine); pStream.println(theLine); if(theLine.equals(".")) break while_loop; } } catch(IOException ignore){} System.out.println("Terminating Connection with " + theConnection.toString()); try{theConnection.close();} catch(IOException ignore){}; } }

  14. Connect to a server (dest. addr., port number) Return input stream Return output stream Get client input from console Write to OutputStream Read from InputStream Close the connection Example: TCP Client Socket -- code fragment try { theSocket = new Socket(hostname,7); theInputStream = new Scanner(theSocket.getInputStream()); theOutputStream = new PrintWriter(theSocket.getOutputStream()); userInput = new Scanner(System.in); while(true){ theLine = userInput.readLine(); if(theLine.equals(".")) {theOutputStream.println(theLine); theSocket.close(); break;} theOutputStream.println(theLine); System.out.println(theInputStream.readLine()); } } catch(UnknownHostException e) System.err.println(e);} catch(IOException e){ }

  15. Concurrent Programming (Concerns) • Mutual Exclusion - must be certain that concurrent processes have mutual exclusive access to shared data. • Race Condition - must avoid situations in which the relative speed of various processes affect the outcome. • Deadlock & Starvation - must avoid situations in which processes are placed in a locked condition indefinitely.

  16. Multiple Threads A program can be divided into separate, independently running subtasks – each of which is called a thread. An underlying mechanism within the operating system is allocating the CPU time to each of the threads.

  17. The Thread constructor takes a Runnable parameter Method sleep can throw an exception Creating Threads Method 2 – Implementing Interface Runnable publicclass ThreadExample2 extends Applet implements Runnable { private Thread t = new Thread(this); ……. publicvoidrun( ) { while (true) { try{ t.sleep(1000); //wake up and do something } catch(InterruptedException e) {/*handle e*/} } } publicvoid init( ) { ….. t.start(); } }

  18. Creating Threads The Runnable Interface used in this example has the following features: • It provides a means for implementing multiple inheritance in Java • It requires that a (new) Thread be specifically created in the applet • The method run( ) is specified in the interface Runnable • (Note!) In Method 1 – where the application extended (inherited from) the class Thread, the run( ) method that the programmer needed to implement was present because Thread also implements interface Runnable. • start( ) is a method in Thread – the Thread object receives the message to perform this operation.

  19. 5 5 5 8 8 8 10 10 10 P1 P1 P1 P2 P2 P2 P3 P3 P3 5] 23] 15] Critical Sections Object semaphore; //synchronized object to “lock” critical section Producer Threads synchronized (semaphore) { total += val; } Critical Section [total = 0] Synchronizing a method public synchronized void someMethod ( ) { body } OR public void someMethod ( ) { synchronized (this) { body } }

  20. Only one thread at a time can access any synchronized method of object buffer The thread gaining access to a buffer method finds it cannot proceed, the thread is momentarily suspended and the lock on the buffer object is opened for other threads to have access to this object. When the critical section is left, the thread notifies other threads that may be suspended waiting access. Synchronizing a method Consider two methods, put( ) and get( ), that allow producers and consumers to insert or remove items from a buffer (object of class Buffer) public synchronizedput (Object x) { while (theBuffer.isFull( ) { try {wait( ); } catch (InterruptedException e) { } } theBuffer.insert(x); notifyAll( ); } public synchronizedObject get( ) { while (theBuffer.isEmpty( ) { try {wait( ); } catch (InterruptedException e) { return null} } Object temp = theBuffer.remove(x); notifyAll( ); return temp; } wait( ) and notify( ) and notifyAll( ) are inherited from Object and available to all classes

  21. Counting Semaphores Counting semaphores issue “tokens” granting a fixed number of threads access to a Container object. publicclass Semaphore { private int s; public Semaphore(int sInit){ s = sInit; //initialized to the number of threads allowed into the critical section at one time } public Semaphore(){ s = 0; } publicsynchronizedvoid sWait() throws InterruptedException { while(s <= 0) try {this.wait();} catch(InterruptedException ignore){} --s; } publicsynchronized void sSignal() { ++s; this.notify(); } }

  22. Producers and Consumers Multiple Producers generate (integer) data that is asynchronously placed in a container (such as a stack, queue, or vector). Multiple Consumers asynchronously retrieve data from the container. We want to ensure that each piece of data generated by a Producer is retrieved by only one of the Consumers. Container (Stack) • Potential Problems • Two or more producers write data to the same location -- (before the first producer updates the size of the container, the second producer reads the original size and overwrites the first entry. The size is updated by both producers, which means that an improper data element appears in the container.) -- eliminated by synchronizing the insert method • Two or more Consumers retrieve the same data element – (This will also cause the size of the container to be reduced twice when only one data item is extracted.) – eliminated by synchronizing the remove method • A Producer and a Consumer perform an insert and a remove at the same time and it becomes a race condition to see which completes first. – prevented by separately synchronizing the two methods • A Consumer tests that the container is not empty as another Consumer is removing the last piece of data from it. – not prevented by synchronizing the two methodsseparately

  23. Producers and Consumers One additional barrier is needed to ensure that only one process is in the critical section at a time. Semaphore notEmpty = new Semaphore(); Semaphore notFull = new Semaphore(containerSize); Semaphore access = new Semaphore(1); publicvoid insert (Object item) { try {notFull.sWait();} catch (InterruptedException e) {} try {access.sWait();} catch (InterruptedException e) {} {body of the method} access.sSignal(); notEmpty.sSignal(); } public Object remove() { try {notEmpty.sWait();} catch (InterruptedException e) {} try {access.sWait();} catch (InterruptedException e) {} {body of the method} access.sSignal(); notFull.sSignal(); }

More Related