Saturday 10 August 2013

Top Most UDP Client Server Networking Program

First write a server program as follows and run on command prompt as below:
java UDPReceive 80


Java Program as below:



package com.myapp.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * This program waits to receive datagrams sent to the specified port. When it
 * receives one, it displays the sending host and prints the contents of the
 * datagram as a string. Then it loops and waits again.
 **/

public class UDPReceive {
public static final String usage = "Usage: java UDPReceive <port>";

public static void main(String args[]) {
try {
if (args.length != 1)
throw new IllegalArgumentException("Wrong number of args");

// Get the port from the command line
int port = Integer.parseInt(args[0]);

// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);

// Create a buffer to read datagrams into. If anyone sends us a
// packet containing more than will fit into this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];

// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

// Now loop forever, waiting to receive packets and printing them.
for (;;) {
// Wait to receive a datagram
dsocket.receive(packet);

// Decode the bytes of the packet to characters, using the
// UTF-8 encoding, and then display those characters.
String msg = new String(buffer, 0, packet.getLength(), "UTF-8");
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);

// Reset the length of the packet before reusing it.
// Prior to Java 1.1, we'd just create a new packet each time.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
System.err.println(usage);
}
}

}


Now Write a Client as below Program

package com.myapp.udp;

import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*Datagram communication is sometimes called UDP, 
 * for Unreliable Datagram Protocol. Sending datagrams is fast, 
 * but the trade-off is that they are not guaranteed to reach their destination. 
 * In addition, multiple datagrams are not guaranteed to travel to their destination 
 * by the same route or to arrive at their destination in the order in which they were
 *  sent. Datagrams are useful when you want low-overhead communication of noncritical 
 *  data and when a stream model of communication is not necessary. For example, 
 *  you might implement a multiuser chat server for a local area network using datagrams.
 To send and receive datagrams, you use the DatagramPacket and DatagramSocket classes. These objects are created and initialized differently, depending on whether they send or receive datagrams
 * 
 * */
public class UDPSend {
public static final String usage = "Usage: java UDPSend <hostname> <port> <msg>...\n"
+ "   or: java UDPSend <hostname> <port> -f <file>";

public static void main(String args[]) {
try {
// Check the number of arguments
if (args.length < 3)
throw new IllegalArgumentException("Wrong number of args");

// Parse the arguments
String host = args[0];
int port = Integer.parseInt(args[1]);

// Figure out the message to send.
// If the third argument is -f, then send the contents of the file
// specified as the fourth argument. Otherwise, concatenate the
// third and all remaining arguments and send that.
byte[] message;
if (args[2].equals("-f")) {
File f = new File(args[3]);
int len = (int) f.length(); // figure out how big the file is
message = new byte[len]; // create a buffer big enough
FileInputStream in = new FileInputStream(f);
int bytes_read = 0, n;
do { // loop until we've read it all
n = in.read(message, bytes_read, len - bytes_read);
bytes_read += n;
} while ((bytes_read < len) && (n != -1));
} else { // Otherwise, just combine all the remaining arguments.
String msg = args[2];
for (int i = 3; i < args.length; i++)
msg += " " + args[i];
// Convert the message to bytes using UTF-8 encoding
message = msg.getBytes("UTF-8");
}

// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);

// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);

// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
} catch (Exception e) {
System.err.println(e);
System.err.println(usage);
}
}

}


Now run your client on command prompt as below 

java UDPSend localhost 80 "hello world"






LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt