DatagramSocket
In this chapter you will learn:
Sending a Datagram
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//from j a va2s.c o m
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress dst = InetAddress.getLocalHost();
int port = 8080;
byte[] outbuf = new byte[1024];
int len = 1024;
DatagramPacket request = new DatagramPacket(outbuf, len, dst, port);
DatagramSocket socket = new DatagramSocket();
socket.send(request);
}
}
Receiving a Datagram
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/*from j a v a 2s .co m*/
public class Main {
public static void main(String[] argv) throws Exception {
byte[] inbuf = new byte[256]; // default size
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
socket.receive(packet);
int numBytesReceived = packet.getLength();
System.out.println(numBytesReceived);
}
}
Read and write with DatagramPacket
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*from j av a 2s .com*/
public class Main {
public static void main(String[] args) throws Exception {
byte[] ary = new byte[128];
DatagramPacket pack = new DatagramPacket(ary, 128);
// read
DatagramSocket sock = new DatagramSocket(1111);
sock.receive(pack);
String word = new String(pack.getData());
System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
System.out.println(word);
sock.close();
// write
sock = new DatagramSocket();
pack.setAddress(InetAddress.getByName(args[1]));
pack.setData(args[2].getBytes());
pack.setPort(1111);
sock.send(pack);
sock.close();
}
}
UDP Port Scanner
import java.net.DatagramSocket;
import java.net.SocketException;
/* j ava2 s. c o m*/
public class MainClass {
public static void main(String[] args) {
for (int port = 1024; port <= 65535; port++) {
try {
// the next line will fail and drop into the catch block if
// there is already a server running on port i
DatagramSocket server = new DatagramSocket(port);
server.close();
} catch (SocketException ex) {
System.out.println("There is a server on port " + port + ".");
}
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket