Upload
peter-richardson
View
256
Download
3
Embed Size (px)
Citation preview
UDP Datagrams and Sockets
Instructors: Fu-Chiung Cheng
(鄭福炯 )Associate Professor
Computer Science & EngineeringTatung University
TCP vs. UDP
• TCP is designed for reliable transmission of data
• If data is lost or damaged in transmission, TCP ensures that the data is resent
• If data arrive out of order, TCP puts them back in the correct order
• If the data is coming too fast for the connection, TCP throttles the speed back so that packets won’t lost
• Thus a program never needs to worry about receiving data that is out of order or incorrect
TCP vs. UDP
• TCP’s reliability comes at a price – speed• Establishing and tearing down TCP
connections can take a fair amount of time• For short transmission (such as HTTP) TCP
may be inefficient• UDP (User Datagram Protocol) is an
alternative protocol for sending data over IP• UDP: very quick but not reliable
TCP vs. UDP
• When you send UDP data, you have no way of knowing – whether it arrived – Whether different pieces of data arrived in
the order in which they are sent
UDP Protocol
• The obvious question to ask is why anyone would ever use an unreliable protocol
• Check some applications– FTP: require reliable transmission– Real-time audio or video stream: UDP– Domain Name system (DNS) (UDP or TCP)
UDP Protocol
• Reliable UDP protocol– If a client sends a short UDP request to a
server, it may assume that the packet is lost if no response is returned
– Applications are responsible for reliable transmission
– Examples:• NFS: Network File System• Trivial FTP• FSP (an FTP)
UDP Protocol
• In Java, DatagramPacket and DatagramSocket classes support UDP protocol.
• DatagramPacket: Data to be sent • DatagramSocket: packet sender/receiver• Sending data:
– Data are put in a DatagramPacket– Send the packet by using DatagramSocket
• Receiving data:– Receive a DatagramPacket object from a
DatagramSocket– Read data of the packet
UDP Protocol
• UDP uses the same kind of socket to send and receive data (I.e. DatagramSocket)– Note that in TCP you have Socket and ServerSocket
• Data to be sent are in UDP packets. Packets’ order is not preserved. – TCP sockets allow you to treat network connection
as a stream.
• A single DatagramSocket can send data to and receive data from many independent hosts– UDP does not have any concept of a connection
between hosts– Multi-casting is possible
DatagramPacket
• UDP datagrams add very little to an IP datagrams
• See Fig 13-1– UDP header adds only eight bytes to the IP
header– Source and destination port numbers– Length– Optional checksum– Each has two bytes
DatagramPacket
• Port numbers are unsigned 2-bytes integers – 65536 possible UDP port per host
• The number of bytes in a datagram is limited to 65535-8– IP header requires 20 bytes + options (0~40 bytes)
(see page 27 of IP datagram format)– Thus theoretical maximum amount 65507– On many platform the actual limit is more likely to be
8K bytes– Very risky: sending UDP packets more than 8KB– For maximum safety UPD packet size <= 512B
Choosing a Datagram Size
• If the network is highly unreliable (e.g. Packet radio network) small packets are perferrable– Small packets are less likely to be corrupted in
transit
• If the network is highly reliable (e.g. Local Area Network) largest packets are perferrable
• 8K bytes is a good compromise for many types of networks
DatagramPacket constructors
• DatagramPacket(byte[] buf, int length) – Constructs a DatagramPacket for receiving packets
of length length.– buf - buffer for holding the incoming datagram.– length - the number of bytes to read (I.e. buf.length).
• DatagramPacket(byte[] buf, int offset, int length)– Constructs a DatagramPacket for receiving packets
of length length, specifying an offset into the buffer.– offset - the offset for the buffer
DatagramPacket constructors
• DatagramPacket(byte[] buf, int length, InetAddress address, int port) – Constructs a datagram packet for sending packets of
length length to the specified port number on the specified host.
– buf - the packet data.– length - the packet length.– address - the destination address.– port - the destination port number.
• DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) – offset - the packet data offset.
DatagramPacket Sending a packet
• Example: sending a packet (page 417) String s = "This is a test."; // data to be sent byte[] data = s.getBytes(); // convert to byte array try { InetAddress ia = InetAddress.getByName("metalab.unc.edu"); int port = 7; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); // send the packet … } catch (UnknownHostException e) { System.err.println(e); }
DatagramPacket Get methods
• InetAddress getAddress()– Returns the IP address of the machine to which
this datagram is being sent or from which the datagram was received
• byte[] getData() – Returns the data received or the data to be sent.
• int getLength() – Returns the length of the data to be sent or the
length of the data received.
DatagramPacket Get methods
• int getOffset() – Returns the offset of the data to be sent or
the offset of the data received.
• int getPort() – Returns the port number on the remote
host to which this datagram is being sent or from which the datagram was received.
• Get methods example: Page 420– DatagramExample.java
DatagramPacket Set methods
• void setAddress(InetAddress iaddr) – Sets the IP address of the machine to which this
datagram is being sent. • void setData(byte[] buf)
– Set the data buffer for this packet. • void setData(byte[] buf, int offset, int length)
– Set the data buffer for this packet. • void setLength(int length)
– Set the length for this packet. • void setPort(int iport)
– Sets the port number on the remote host to which this datagram is being sent.
DatagramSocket
• To send or receive a DatagramPacket, one needs to open a datagram socket (i.e. DatagramSocket).
• All datagram sockets are bound to a local port– Datagram sockets listen for incoming data on
that port– Or send data to that port
DatagramSocket
• For datagram servers, clients need to know on which port a server is listening for incoming datagrams– Servers must specify the local port on which it will
listen.
• For datagram clients, any unused port can be used to send requests (a datagram packet) to server
• There is no distinction between client sockets and server sockets. – One class only – DatagramSocket class
DatagramSocketconstructor
• DatagramSocket() – Constructs a datagram socket and binds it to any available
port on the local host machine.– Good for clients (may be not good for UDP Servers)
• DatagramSocket(int port) – Constructs a datagram socket and binds it to the specified
port on the local host machine.
• DatagramSocket(int port, InetAddress laddr) – Creates a datagram socket, bound to the specified local
address.
DatagramSocketSend and Receive Datagrams
• void send(DatagramPacket p) – Sends a datagram packet from this socket. DatagramSocket ds = new DatagramSocket(); DatagramPacket dp = new DatagramPacket(data,
data.length, remote, port); ds.send(dp);
• void receive(DatagramPacket p) – Receives a datagram packet from this socket. DatagramSocket server = new DatagramSocket(port); DatagramPacket packet = new DatagramPacket(buffer,
buffer.length); server.receive(packet);
DatagramSocketSend and Receive Datagrams
• Example 13-3 UDP Discard Client (UDPDiscardClient.java)– Read lines of user input– Send them to a discard server
• Example 13-4 UDP Discard Server (UDPDiscardServer.java)– Receive a single UDP datagram – Print out the info on the datagram
DatagramSocketclose method
• void close() – Closes this datagram socket.– Free the port occupied by that sockettry { DatagramSocket socket = new
DatagramSocket(); socket.close(); } catch (SocketException e) { System.err.println(e);}
DatagramSocketManaging connections
• Datagram sockets can talk to anyone by default• You may restrict the connections by using connect
method.• Possible Applications:
– Applets are allowed to send datagrams to and receive datagrams from the applet host.
– A NFS (network file system) client should accept packets only from the server it is talking to.
– A networked game should listen to datagrams only from the people playing the game
DatagramSocketManaging connections
• void connect(InetAddress address, int port)– Connects the socket to a remote address for this socket. – When a socket is connected to a remote address, packets
may only be sent to or received from that address. – Attempt to send packets to a different host or port will throw
IllegalArgumentException.– Packets received from a different host or port will be
discarded without an exception or other notification– By default a datagram socket is not connected. – When a socket is connected, receive and send will not
perform any security checks on incoming and outgoing packets, other than matching the packet's and the socket's address and port.
DatagramSocketManaging connections
• void disconnect() – Disconnects the socket. – This does nothing if the socket is not connected.– The disconnected DatagramSocket can once
again send packets to and receive packets from any host and port.
DatagramSocketGet methods
• InetAddress getInetAddress() – Returns the address to which this socket is connected.
• InetAddress getLocalAddress() – Gets the local address to which the socket is bound.
• int getLocalPort() – Returns the port number on the local host to which this
socket is bound.
• int getPort() – Returns the port for this socket.
DatagramSocketOptions
• int getReceiveBufferSize() – Get value of the SO_RCVBUF option for this
DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.
– Larger buffers tend to improve performance (i.e. LAN)
• void setReceiveBufferSize(int size) – Sets the SO_RCVBUF option to the specified
value for this DatagramSocket.
DatagramSocketOptions
• int getSendBufferSize() – Get value of the SO_SNDBUF option for this
DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.
• Void setSendBufferSize(int size) – Sets the SO_SNDBUF option to the specified
value for this DatagramSocket.
DatagramSocketOptions
• int getSoTimeout() – Retrive setting for SO_TIMEOUT.– SO_TIMEOUT in milliseconds. – With this option set to a non-zero timeout, a call to
receive() for this DatagramSocket will block for only this amount of time.
– A timeout of zero is interpreted as an infinite timeout.– If the timeout expires, a java.io.InterruptedIOException is
raised, though the ServerSocket is still valid.
• void setSoTimeout(int timeout)– Enable/disable SO_TIMEOUT with the specified timeout,
in milliseconds.
Useful UDP Applications
• When an IP packet is received by a host, the host determines whether the packet is a TCP or UDP datagram by inspecting IP header
• TCP and UDP ports are independent– TCP and UDP servers can share the same port
number without problems.
• By convention, if a service has both TCP and UDP implementations, it uses the same port for both
Useful UDP ApplicationsSimple UDP clients
• Several Internet services need to know the client’s address and port; they discard any data the client sends in its datagrams:– Daytime (TCP and UDP port: 13)– Quote of the day– Time (TCP and UDP port: 37)– Chargen (TCP and UDP port: 19)
• Clients for these protocols simply send a UDP datagram to the servers and read the response that comes back
Useful UDP ApplicationsSimple UDP clients
• Example 13-5 UDPPoke.java
• Run the UDDPoke– java UDPPoke vision.poly.edu 19
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcde??
– java UDPPoke vision.poly.edu 13
Mon Apr 16 22:11:47 2001
Useful UDP Applications UDP Server
• Example 13-7 UDPServer.java (page 440)• UDPServer is designed for reuse• UDPServer is a thread• Fields
– int bufferSize: buffer size of DatagramPacket– DatagramSocket ds: the datagram socket
• Methods:– respond(packet): abstract method– run(): read packet and call respond()
Useful UDP Applications UDP Server
• Example 13-8 FastUDPDiscardServer.java (page 441) public void respond(DatagramPacket packet) {}
• Example 13-9 LoggingUDPDiscardServer.java (page 442)public void respond(DatagramPacket packet) { byte[] data = new byte[packet.getLength()]; System.arraycopy(packet.getData(),0,data,0,
packet.getLength()); try { String s = new String(data, "ASCII"); System.out.println(packet.getAddress() + " at port " + packet.getPort() + " says " + s); } catch (java.io.UnsupportedEncodingException e) { } }
Useful UDP Applications UDP Server
Example 13-10 UDPEchoServer.java (page 443) public void respond(DatagramPacket incoming) { try { DatagramPacket outgoing = new DatagramPacket( incoming.getData(), incoming.getLength(), incoming.getAddress(), incoming.getPort()); ds.send(outgoing); System.out.println(incoming.getLength()); } catch (IOException e) { System.err.println(e); } }
Useful UDP Applications UDP Server
Example 13-11 UDPDaytimeServer.java (page 444) public void respond(DatagramPacket packet) { try { Date now = new Date(); String response = now.toString() + "\r\n"; byte[] data = response.getBytes("ASCII"); DatagramPacket outgoing = new DatagramPacket(data, data.length, packet.getAddress(), packet.getPort()); ds.send(outgoing); } catch (IOException e) { System.err.println(e); } }