Java Networking Datagrams Tutorial
Client server communication with Datagrams
Java Networks Home
Generally, Datagrams are transmits packets of information between machines. Once the datagram has released to its intended target, there is no assurance that it will arrive without loss of data. Java implements datagrams on top of UDP protocol by using 2 classes. They are..
1.DatagramSocket
constructors DatagramSocket()throws SocketException DatagramSocket(int port)throws SocketException DatagramSocket(int port,InetAddrss ipaddress)throws SocketException DatagramSocket(SocketAddress address)throws SocketException SocketAddress
It is an abstract class implemented by concrete class InetSocketAddress. It encapsulates an IP address with a port no. methods void send(DatagramPacket packet) throws IOException void receive(DatagramPacket packet) throws IOException
2.DatagramPacket
its object is the data container. DatagramPacket(byte data[], int size) DatagramPacket(byte data[], int offset,int size) DatagramPacket(byte data[], int size,InetAddress ipAddress,int port) DatagramPacket(byte data[], int offset, int size,InetAddress ipAddress,int port) methods InetAddress getAddress() byte[] getData() setData(byte[]) int getLength() getPort() setPort()
The following ex. implements a very simple networked communication client and server.
Message are typed into the window at the server and written across the network to the
client side, where they are display.
// Demonstrate Datagrams. import java.net.*; class WriteServer { public static int serverPort = 666; public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[] = new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while (true) { int c = System.in.read(); switch (c) { case -1: System.out.println("Server Quits."); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos, InetAddress.getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++] = (byte) c; } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); System.out.println(new String(p.getData(), 0, p.getLength())); } } public static void main(String args[]) throws Exception { if(args.length == 1) { ds = new DatagramSocket(serverPort); TheServer(); } else { ds = new DatagramSocket(clientPort); TheClient(); } } }
This sample program is restricted by the DatagramSocket constructor to running between two ports on the local machine. To use the program, In one window run the program as shown below
c:\>java WriteServer
this will be the client. Then run in another window..
c:\>java WriteServer 1
This will be the server. Anything that is typed in the server window will be sent to the client window after a newline is received.
Note This example requires that your computer be connected to the Internet.
Comments
Post a Comment