1 / 44

Block 4: The Concept of Socket API

Block 4: The Concept of Socket API. Jin Sa. Outline of block 4. Introduction to the concept of socket API Datagram socket and Stream socket Stream mode socket API classes: ServerSocket, Socket Key methods in the stream mode Logics in the server and the client Program flow

jhendley
Télécharger la présentation

Block 4: The Concept of Socket API

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. Block 4: The Concept of Socket API Jin Sa Client-server Programming

  2. Outline of block 4 • Introduction to the concept of socket API • Datagram socket and Stream socket • Stream mode socket • API classes: ServerSocket, Socket • Key methods in the stream mode • Logics in the server and the client • Program flow • Simple example • Datagram socket • API classes: DatagramSocket, DatagramPacket • Logics in the sender and the receiver • Data structure in the sender and the receiver • Key methods in the datagram mode • Program flowing in the sender and the receiver processes • Simple examples Client-server Programming

  3. Introduction • The socket API is an Interprocessing Communication (IPC) programming interface. • It is a de facto standard for programming IPC, and is the basis of more sophisticated IPC interface such as remote procedure call and remote method invocation. Client-server Programming

  4. The conceptual model of the socket API Client-server Programming

  5. The socket API • A socket API provides a programming construct termed a socket. • A process wishing to communicate with another process must create an instance of such a construct • The two processes then issues operations provided by the API to send and receive data through the sockets. Client-server Programming

  6. Datagram sockets and stream sockets • A socket programming construct can use either the UDP or TCP protocol. • Sockets that use UDP for transport are known as datagram sockets, while sockets that use TCP are termed stream sockets. Client-server Programming

  7. The Stream-mode Socket API • The stream socket API provides a model of data transfer based on the stream-mode I/O. • Stream-mode sockets support connection-oriented communication. Client-server Programming

  8. Stream-mode Socket API • A stream-mode socket is established for data exchange between two specific processes. • Data stream is written to the socket at one end, and read from the other end. Client-server Programming

  9. Client-server Programming

  10. Java stream-mode Socket API In Java, the stream-mode socket API is provided with two classes: • ServerSocket: for accepting connections; we will call an object of this class a connection socket. • Socket: for data exchange; we will call an object of this class a data socket. Client-server Programming

  11. Server and Client • The API for stream communication assumes that when two processes are establishing a connection, one plays the role of a client and the other a server, but thereafter they are peers. Client-server Programming

  12. Server and Client • The server creates a listening socket (serverSocket) bound to a server port and wait for client to request a connection. • The client creates a stream socket and makes a connection request to a server at its server port. • When a connection request is accepted, the server creates a new stream socket for communicating with the client. Client-server Programming

  13. Server and Client • The pair of stream sockets in client and server are connected by a pair of streams, one in each direction. • Each socket has an input stream and an output stream. • To send information from one process to the other, the sending process writes the information to its output stream, and the other process reads from its input stream. Client-server Programming

  14. Key methods in the ServerSocket class • ServerSocket(int port) constructor • Socket accept() listens for a connection request and accepts it. A blocking operation. • void close() closes this server socket • void setSoTimeout(int milliseconds) sets a timeout period to avoid infinite blocking Client-server Programming

  15. Key methods in the Socket class • Socket(InetAddress addr, int port) constructor creates a socket and connects to addr and port • void close() closes the socket • InputStream getInputStream() returns an input stream so that data may be read from the socket. A read operation on the InputStream is blocking. • OutputStream getOutputStream() returns an output stream so that data may be written to the socket. A write operation on the OutputStream is nonblocking. Client-server Programming

  16. Stream-mode Socket API program flow Connection listener (server) Connection requester (client) Create a connection socket and listen for connection requests Accept a connection and create a data socket for reading from or writing to the socket stream Get an input stream for reading from the socket Get an output stream for writing to the socket Read from stream Write to the stream Repeat the read or write Close the data socket Close the connection socket Create a data socket and request a connection Get an output stream for writing to the socket Get an input stream for reading from the socket Write to the stream Read from the stream Repeat the read or write Close the data socket Client-server Programming

  17. Example 4 Event Diagram (skip) Client-server Programming

  18. Simple example • Example4Acceptor – version 1 • Create a serverSocket and listens for requests • Accept a request and, as a result, create an instance of a data socket • Get an output stream from the data socket • Send a message “hello from server” to the requestor by writing to the output stream • Close data socket • Close serverSocket • Example4Requestor – version 1 • Requests a connection for the Acceptor process by creating an instance of a data socket with the acceptor’s address and port number • Get an input stream from the data socket • Receive the message from the Acceptor by reading from the input stream • Close data socket Client-server Programming

  19. In class exercises • Study the two programs: Example4Acceptor.java and Example4Requestor.java • Explain what happens when you run Example4Requestor first and then Example4Acceptor • Explain what happens when you run Example4Acceptor first and then Example4Requestor Client-server Programming

  20. Notes on Example4 • Although the example shows Acceptor as the sender of data and the Requestor as the receiver, the role can be reversed. In that case, the Requestor will use getOutputStream to write to the socket, while the Acceptor will use getInputStream to read from the socket. • In fact, either process can both read and write to the stream. Client-server Programming

  21. Simple examples • Example4Acceptor • Example4Requestor • Version 1: Example4Acceptor only send once and Example4Requestor only receive once • Version 2: Example4Acceptor send and receive; similarly Example4Requestor • Version 3: Example4Acceptor has more than one connection. Client-server Programming

  22. Modify Example4 • Modify Acceptor so that it can receive a message; and modify Requestor so that it also sends a message. (see code in streamsocket) • Modify the programs to introduce another requestor so that the Acceptor will accept another connection from the second requestor once the data socket with the first requestor is closed. • Try to send more messages from Requestor • Try to receive more message from Acceptor • Try to keep connection open in Acceptor and ready to receive another request from requestor2 Client-server Programming

  23. Datagram socket • The datagram socket API supports the exchange of discrete units of data • Datagram sockets usually are used to support connectionless communication at the application layer. Client-server Programming

  24. The Java Datagram Socket API In Java, two classes are provided for the datagram socket API: • the DatagramSocketclass for the sockets. • the DatagramPacket class for the datagram exchanged. Client-server Programming

  25. The Java Datagram Socket API A process wishing to send or receive data using this API must instantiate a DatagramSocket object. Each socket is said to bebound to a UDP port of the machine local to the process Client-server Programming

  26. The Java Datagram Socket API To send a datagram to another process, a process: • creates a DatagramPacket object that represents the datagram itself. This object carries • the payload data as a reference to a byte array, • the destination address (the host ID and port number to which the receiver’s socket is bound. • issues a call to a send method in the DatagramSocketobject, specifying a reference to the DatagramPacket object as an argument Client-server Programming

  27. The Java Datagram Socket API • In the receiving process, a DatagramSocket object must also be instantiated and bound to a local port. (The port number must agree with that specified in the datagram packet of the sender. ) • To receive datagrams sent to the socket, the process creates a datagramPacket object which references a byte array and calls a receivemethod in its DatagramSocket object, specifying as argument a reference to the DatagramPacket object. Client-server Programming

  28. The Data Structures in the sender and receiver programs for datagram socket Client-server Programming

  29. Key Methods and Constructors for Datagram -- DatagramSocket • DatagramSocket() constructor, used if no need to receive datagram • DatagramSocket(int port) constructor, used if need to receive packet. The port number can then be specified in the datagram packet sent by the other process. • void close() to close the datagram socket Client-server Programming

  30. Key Methods and Constructors for Datagram-- DatagramSocket • void receive(DatagramPacket p) to receive a datagram packet, p will refer to the packet • void send(DatagramPacket p) to send the datagram packet pointed by p using this datagram socket • void setSoTimeout(int timeout) Sets a timeout period for the blocking receive operations Client-server Programming

  31. Key Methods and Constructors for Datagram -- DatagramPacket • DatagramPacket(byte[] buf,int l) constructor for receiving packets of length l, data received will be stored in buf • DatagramPacket(byte[] buf,int l,InetAddress ipAddress, int port) constructor for sending packets to the socket bound to the port number on the receiving host. Client-server Programming

  32. The program flow in the sender and receiver programs Receiver program Sender program Create a datagram socket (binds it to a local port) Place data in a byte array Create a datagram packet, specifying the data array and the receiver’s address (IP address and port same as in the receiver’s port number) Invoke the send method of the socket with a reference to the datagram packet Create a datagram socket and bind it to a local port number Create a byte array for receiving the data Create a datagram packet, specifying the data array Invoke the receive method of the socket with a reference to the datagram packet Client-server Programming

  33. Setting timeout • To avoid indefinite blocking, a timeout can be set with a socket object. • Once set, the timeout will be in effect for all blocking operations. Client-server Programming

  34. Example • Example1Sender • Create a datagram socket • Put the message “Hello!” in a byte array • Create a data packet with the receiver’s address and port number, and the byte array • Send datagram in the packet through the datagram socket • Example1Receiver • Create a datagram socket bound to a port (12345) • Create a datagram packet includes a reference to a byte array • Receive a data packet through the datagram socket Client-server Programming

  35. In class exercises • Study the two programs: Example1Sender.java and Example1Receiver.java (send is non blocking, and receive is blocking) • Explain what happens when you run Example1Receiver first and then Example1Sender • Explain what happens when you run Example1Sender first and then Example1Receiver • Explain what happens when you run Example1Receiver twice without running Example1Sender. • Explain the effect of setting a timeout. • Explain what happens when you replace the message “hello!” with “hello, how are you?” Client-server Programming

  36. Issues to remember • Synchronisation of the events, e.g. send before receive or receive before send • If infinitely blocked, use timeout, length of the timeout period • Size of the buffer for holding the data Client-server Programming

  37. More Exercises on Datagram Socket (skip) • Modify the programs so that • Example1Sender will be renamed as ProcessA; it will send the message “hello” from process A to process B; and then receive a message from process B. • Example1Receiver will be renamed as ProcessB; it will receive a message from process A; and then send the message “bye” to process A. a) Explain what will happen if we run ProcessB first and then ProcessA b) Explain what will happen if we run ProcessA first and then ProcessB Client-server Programming

  38. Some Notes on Datagram Socket • Sockets normally provide non-blocking send and blocking receive • The method receive blocks until a datagram packet is received as seen in Example1Receive, unless it sets a time out period. Client-server Programming

  39. Providing abstraction • In software engineering, we often define our systems in a layered approach by providing more abstract API. • We can define our own datagram socket which hides details such as data packet, byte arrays. Client-server Programming

  40. MyDatagramSocket • Methods are: • MyDatgramSocket(int portNumber) constructor • sendMessage(String receiverAddr, int receiverPort,String message) • String receiveMessage() Client-server Programming

  41. sendMessage(…) InetAddress receiverHost = InetAddress.getByName(receiverAddr); byte[ ] sendBuffer = message.getBytes( ); DatagramPacket datagram = new DatagramPacket(sendBuffer, sendBuffer.length, receiverHost, receiverPort); send(datagram); Client-server Programming

  42. receiveMessge() byte[ ] receiveBuffer = new byte[MAX_LEN]; DatagramPacket datagram = new DatagramPacket(receiveBuffer, MAX_LEN); receive(datagram); String message = new String(receiveBuffer); return message; Client-server Programming

  43. Example1Sender_1 public static void main(String[] args) { try { String receiverAddr = "localhost"; int receiverPort = 12345; String message = "hello!"; System.out.println("This is the sender program"); MyDatagramSocket mySocket = new MyDatagramSocket(54321); mySocket.sendMessage(receiverAddr, receiverPort,message); mySocket.close( ); } // end try Client-server Programming

  44. Example1Receiver_1 public static void main(String[] args) { int port =12345; try { System.out.println("This is the receiver_1 program"); MyDatagramSocket mySocket = new MyDatagramSocket(port); String message = mySocket.receiveMessage(); System.out.println("message received is: “ +message); mySocket.close( ); } // end try Client-server Programming

More Related