UDPSendDemo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException; public class UDPSendDemo
{ /**
* @param args
*/
public static void main(String[] args)
{
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in)); String line = null; try
{
while ((line = br.readLine()) != null)
{
byte[] buf = line.getBytes();
if (line.equals("quit"))
break;
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("192.168.0.101"), 8638); ds.send(dp); }
ds.close(); } catch (IOException e)
{
e.printStackTrace();
} } catch (SocketException e)
{
e.printStackTrace(); } } }
UDPReceiveDemo:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException; public class UDPReceiveDemo
{
public static void main(String[] args)
{ try
{
DatagramSocket ds = new DatagramSocket(8638); while (true)
{
byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); try
{
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength()); System.out.println(ip + ":: " + data); } catch (IOException e)
{
e.printStackTrace();
} }
} catch (SocketException e)
{
e.printStackTrace();
}
}
}