1、12/20/2022Distributed Computing,M.L.Liu1The Socket APIMei-Ling Liu12/20/2022Distributed Computing,M.L.Liu2Introduction The socket API is an Interprocessing Communication(IPC)programming interface originally provided as part of the Berkeley UNIX operating system.It has been ported to all modern opera
2、ting systems,including Sun Solaris and Windows systems.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.12/20/2022Distributed Computing,M.L.Liu3The conceptual model of the socket API a socket
3、Process AProcess B12/20/2022Distributed Computing,M.L.Liu4The socket API A socket API provides a programming construct termed a socket.A process wishing to communicate with another process must create an instance,or instantiate,such a construct The two processes then issues operations provided by th
4、e API to send and receive data.12/20/2022Distributed Computing,M.L.Liu5Connection-oriented&connectionless datagram socket A socket programming construct can make use of either the UDP or TCP protocol.Sockets that use UDP for transport are known as datagramdatagram sockets sockets,while sockets that
5、use TCP are termed stream socketsstream sockets.Because of its relative simplicity,we will first look at datagram sockets,returning to stream sockets after we have introduced the client-server model in Chapter 5.12/20/2022Distributed Computing,M.L.Liu6Connection-oriented&connectionless datagram sock
6、etDatagram sockets can support both connectionlessconnectionless and connection-orientedconnection-oriented communication at the application layer.This is so because even though datagrams are sent or received without the notion of connections at the transport layer,the runtime runtime support of the
7、 socket APIsupport of the socket API can create and maintain logical connections for datagrams exchanged between two processes,as you will see in the next section.(The runtime support of an API is a set of software that is bound to the program during execution in support of the API.)12/20/2022Distri
8、buted Computing,M.L.Liu7Connection-oriented&connectionless datagram socketProcess AsocketAPI runtimesupportProcess BsocketAPI runtimesupporttransport layer softwaretransport layer softwarea datagrama logical connection created and maintainedby the runtime support of the datagramsocket APIProcess Aso
9、cketAPI runtimesupportProcess BsocketAPI runtimesupporttransport layer softwaretransport layer softwareconnectionless datagram socketconnection-oriented datagram socket12/20/2022Distributed Computing,M.L.Liu8The Java Datagram Socket APIIn Java,two classes are provided for the datagram socket API:1.t
10、he DatagramSocket class for the sockets.2.the DatagramPacketDatagramPacket class for the datagram exchanged.A process wishing to send or receive data using this API must instantiate a DatagramSocket object,or a socket in short.Each socket is said to be boundbound to a UDP port of the machine local t
11、o the process 12/20/2022Distributed Computing,M.L.Liu9The Java Datagram Socket APITo send a datagram to another process,a process:creates an object that represents the datagram itself.This object can be created by instantiating a DatagramPacket object which carries1.(i)the payload data as a referenc
12、e to a byte array,and 2.(ii)the destination address(the host ID and port number to which the receivers socket is bound.issues a call to a sendsend method in the DatagramSocketDatagramSocket object,specifying a reference to the DatagramPacketDatagramPacket object as an argument12/20/2022Distributed C
13、omputing,M.L.Liu10The Java Datagram Socket API In the receiving process,a DatagramSocketDatagramSocket 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 cr
14、eates a datagramPacketdatagramPacket object which references a byte array and calls a receive receive method in its DatagramSocketDatagramSocket object,specifying as argument a reference to the DatagramPacketDatagramPacket object.12/20/2022Distributed Computing,M.L.Liu11The Data Structures in the se
15、nder and receiver programsa byte arraya DatagramPacket objectreceiversaddressa DatagramSocket objectsender processa byte arraya DatagramPacket objecta DatagramSocket objectreceiver processsendreceiveobject referencedata flow12/20/2022Distributed Computing,M.L.Liu12The program flow in the sender and
16、receiver programs create adatagram socket and bind it to any local port;place data in a byte array;create adatagram packet,specifying the data array and the receivers address;invoke the send method of the socket with a reference to thedatagram packet;create adatagram socket and bind it to a specific
17、 local port;create a byte array for receiving the data;create adatagram packet,specifying the data array;invoke the receive method of the socket with a reference to thedatagram packet;sender programreceiver program12/20/2022Distributed Computing,M.L.Liu13Event synchronization with the connectionlss
18、datagram socketsAPIserverclientrequestresponseblockedsendreceivereceivesendblocking receive,nonblocking sendin a request-responseprotocolif data is sent before a correspondingreceive operation is issued,the data willbe discarded by the runtime supportand will not be received.12/20/2022Distributed Co
19、mputing,M.L.Liu14Setting timeoutTo avoid indefinite blocking,a timeout can be set with a socket object:void setSoTimeout(inttimeout)Setatimeoutfortheblockingreceivefromthissocket,inmilliseconds.Once set,the timeout will be in effect for all blocking operations.12/20/2022Distributed Computing,M.L.Liu
20、15Key Methods and ConstructorsMethod/Constructor Description DatagramPacket(byte buf,int length)Construct a datagram packet for receiving packets of length length;data received will be stored in the byte array reference by buf.DatagramPacket(byte buf,int length,InetAddress address,int port)Construct
21、 a datagram packet for sending packets of length length to the socket bound to the specified port number on the specified host;data received will be stored in the byte array reference by buf.DatagramSocket()Construct a datagram socket and binds it to any available port on the local host machine;this
22、 constructor can be used for a process that sends data and does not need to receive data.DatagramSocket(int port)Construct a datagram socket and binds it to the specified port on the local host machine;the port number can then be specified in a datagram packet sent by a sender.void close()Close this
23、 datagramSocket object void receive(DatagramPacket p)Receive a datagram packet using this socket.void send(DatagramPacket p)Send a datagram packet using this socket.void setSoTimeout(int timeout)Set a timeout for the blocking receive from this socket,in milliseconds.12/20/2022Distributed Computing,M
24、.L.Liu16The coding/Excerpt from a receiver programDatagramSocket ds=new DatagramSocket(2345);DatagramPacket dp=new DatagramPacket(buffer,MAXLEN);ds.receive(dp);len=dp.getLength();System.out.Println(len+bytes received.n);String s=new String(dp.getData(),0,len);System.out.println(dp.getAddress()+at po
25、rt +dp.getPort()+says +s);/Excerpt from the sending processInetAddressreceiverHost=InetAddress.getByName(localHost);DatagramSocket theSocket=new DatagramSocket();String message=Hello world!;byte data=message.getBytes();data=theLine.getBytes();DatagramPacket thePacket =new DatagramPacket(data,data.le
26、ngth,receiverHost,2345);theSocket.send(theOutput);12/20/2022Distributed Computing,M.L.Liu17Connectionless socketsWith connectionless sockets,it is possible for multiple processes to simultaneously send datagrams to the same socket established by a receiving process,in which case the order of the arr
27、ival of these messages will be unpredictable,in accordance with the UDP protocol Process AProcess BProcess CProcess AProcess BProcess C Figure 3a Figure 3ba connectionlessdatagram socket12/20/2022Distributed Computing,M.L.Liu18Code samples Example1Sender.java,ExampleReceiver.java MyDatagramSocket.ja
28、va,Example2SenderReceiver.java,Example2ReceiverSender.java 12/20/2022Distributed Computing,M.L.Liu19Connection-oriented datagram socket APIIt is uncommon to employ datagramIt is uncommon to employ datagram sockets sockets for connection-oriented communicationfor connection-oriented communication;the
29、 connection provided by this API is rudimentary and typically insufficient for applications that require a true connection.Stream-mode sockets,which will be introduced later,are more typical and more appropriate for connection-oriented communication.12/20/2022Distributed Computing,M.L.Liu20Methods c
30、alls for connection-oriented datagram socketA connection is made for a socket with a remote socket.Once a socket is connected,it can only exchange data with the remote socket.If a datagram specifying another address is sent usingthe socket,an IllegalArgumentException will occur.If a datagram from an
31、other socket is sent to this socket,The data will be ignored.Method/Constructor Description public void connect(InetAddress address,int port)Create a logical connection between this socket and a socket at the remote address and port.public void disconnect()Cancel the current connection,if any,from t
32、his socket.12/20/2022Distributed Computing,M.L.Liu21Connection-oriented Datagram SocketThe connection is unilateralunilateral,that is,it is enforced only on one side.The socket on the other side is free to send and receive data to and from other sockets,unless it too commits to a connection to the o
33、ther socket.See Example3Sender,Example3Receiver.12/20/2022Distributed Computing,M.L.Liu22The Stream-mode Socket API The datagramdatagram socket socket API supports the exchange of discrete units of data(that is,datagrams).the stream socketstream socket API provides a model of data transfer based on
34、the stream-mode I/O of the Unix operating systems.By definition,a stream-mode socket supports connection-oriented communication only.12/20/2022Distributed Computing,M.L.Liu23Stream-mode Socket API(connection-oriented socket API).a data streamprocesswrite operationread operationP1P2a stream-mode data
35、 socket12/20/2022Distributed Computing,M.L.Liu24Stream-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.A stream socket cannot be used to communicate with more than one pro
36、cess.12/20/2022Distributed Computing,M.L.Liu25Stream-mode Socket APIIn Java,the stream-mode socket API is provided with two classes:Server socket: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 so
37、cket.12/20/2022Distributed Computing,M.L.Liu26Stream-mode Socket API program flowconnection listener(server)create a connection socketand listen for connectionrequests;accept a connection;creates a data socket for reading fromor writing to the socket stream;get an input stream for readingto the sock
38、et;read from the stream;get an output stream for writingto the socket;write to the stream;close the data socket;close the connection socket.connection requester(server)create a data socketand request for a connection;get an output stream for writingto the socket;write to the stream;get an input stre
39、am for readingto the socket;read from the stream;close the data socket.12/20/2022Distributed Computing,M.L.Liu27The server(the connection listener)serverclient 1connection operationsend/receive operatonA server uses two sockets:one for accepting connections,another for send/receiveclient 2connection
40、 socketdata socket12/20/2022Distributed Computing,M.L.Liu28Key methods in the ServerSocket classMethod/constructor Description ServerSocket(int port)Creates a server socket on a specified port.Socket accept()throws IOException Listens for a connection to be made to this socket and accepts it.The met
41、hod blocks until a connection is made.public void close()throws IOException Closes this socket.void setSoTimeout(int timeout)throws SocketException Set a timeout period(in milliseconds)so that a call to accept()for this socket will block for only this amount of time.If the timeout expires,a java.io.
42、InterruptedIOException is raised Note:Accept is a blocking operation.12/20/2022Distributed Computing,M.L.Liu29Key methods in the Socket classMethod/constructor Description Socket(InetAddress address,int port)Creates a stream socket and connects it to the specified port number at the specified IP add
43、ress void close()throws IOException Closes this socket.InputStream getInputStream()throws IOException Returns an input stream so that data may be read from this socket.OutputStream getOutputStream()throws IOException Returns an output stream so that data may be written to this socket.void setSoTimeo
44、ut(int timeout)throws SocketException Set a timeout period for blocking so that a read()call on the InputStream associated with this Socket will block for only this amount of time.If the timeout expires,a java.io.InterruptedIOException is raised A read operation on the InputStream is blocking.A writ
45、e operation is nonblocking.12/20/2022Distributed Computing,M.L.Liu30Connection-oriented socket API-3Server establishes asocketsd1 w ith localaddress,then listensfor incomingconnection onsd1Client establishesa socket w ithremote(servers)address.serverclient1.2.Server accepts the connection request an
46、d creates a new socketsd2 as a result.sd1sd1sd212/20/2022Distributed Computing,M.L.Liu31sd1sd2sd1sd23.Server issues receive operation using sd2.Client issuessend operation.4.Server sends response using sd2.sd15.When the protocol has completed,server closes sd2;sd1 is used to accept the next connecti
47、onClient closes itssocket when theprotocol hascompletedConnection-oriented socket API-312/20/2022Distributed Computing,M.L.Liu32Connectionless socket APIP1P2P2 establishesa local socketP1 establishesa local socketP2 sends a datagramaddressed to P1P1 issues areceive operationto receive thedatagram.12
48、/20/2022Distributed Computing,M.L.Liu33Example 4 Event Diagramacceptwriteclosedata socketcloseconnection socketconnect request(from Socket constructor)readConnectionAcceptorConnectionRequestortimeprocess executingprocess suspendedclose socketan operationmessage12/20/2022Distributed Computing,M.L.Liu
49、34Example4 try nt portNo;String message;/instantiates a socket for accepting connection ServerSocket connectionSocket=new ServerSocket(portNo);Socket dataSocket=connectionSocket.accept();/get a output stream for writing to the data socketOutputStream outStream=dataSocket.getOutputStream();/create a
50、PrinterWriter object for character-mode outputPrintWriter socketOutput=new PrintWriter(new OutputStreamWriter(outStream);/write a message into the data streamsocketOutput.println(message);/The ensuing flush method call is necessary for the data to /be written to the socket data stream before the /so
侵权处理QQ:3464097650--上传资料QQ:3464097650
【声明】本站为“文档C2C交易模式”,即用户上传的文档直接卖给(下载)用户,本站只是网络空间服务平台,本站所有原创文档下载所得归上传人所有,如您发现上传作品侵犯了您的版权,请立刻联系我们并提供证据,我们将在3个工作日内予以改正。