public static void main (String [] argv) throws

have a peer DatagramSocket object that can be obtained by calling the socket() method. DatagramChannel objects can act both as server (listener) and client (sender). If you want the newly created channel to listen, it must first be bound to a port or address/port combination. Binding is no different with DatagramChannel than it is for a conventional DatagramSocket; it’s delegated to the API on the peer socket object: DatagramChannel channel = DatagramChannel.open(); DatagramSocket socket = channel.socket(); socket.bind (new InetSocketAddress (portNumber)); DatagramChannels are connectionless. Each datagram is a self-contained entity, with its own destination address and a data payload independent of every other datagram’s. Unlike stream-oriented sockets, a DatagramChannel can send individual datagrams to different destination addresses. Likewise, a DatagramChannel object can receive packets from any address. Each datagram arrives with information about where it came from (the source address). A DatagramChannel that is not bound can still receive packets. When the underlying socket is created, a dynamically generated port number is assigned to it. Binding requests that the channel’s associated port be set to a specific value (which may involve security checks or other validation). Whether the channel is bound or not, any packets sent will contain the DatagramChannel’s source address, which includes the port number. Unbound DatagramChannels can receive packets addressed to their port, usually in response to a packet sent previously by that channel. Bound channels receive packets sent to the well-known port to which they’ve bound themselves. The actual sending or receiving of data is done by the send() and receive() methods: public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel { // This is a partial API listing public abstract SocketAddress receive (ByteBuffer dst) throws IOException; public abstract int send (ByteBuffer src, SocketAddress target) } The receive() method copies the data payload of the next incoming datagram into the provided ByteBuffer and returns a SocketAddress object to indicate where it came from. If the channel is in blocking mode, receive() may sleep indefinitely until a packet arrives. If nonblocking, it returns null if no packets are available. If the packet contains more data than will fit in your buffer, any excess will be silently discarded. If the ByteBuffer you provide does not have sufficient remaining space to hold the packet you’re receiving any bytes that don’t fit will 112
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

Comments are closed.