Java 网络编程 之 UDP
http://www.verejava.com/?id=16994911008925
服务器端
package com.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPServer
{
public static void main(String[] args)
{
try
{
DatagramSocket ds=new DatagramSocket(9001);
System.out.println("在9001端口监听...");
byte[] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b,0,b.length);
ds.receive(dp);
byte[] data=dp.getData();
String content=new String(data,0,dp.getLength());
System.out.println(content);
byte[] b2="ok".getBytes();
DatagramPacket dp2=new DatagramPacket(b2,0,b2.length);
dp2.setPort(dp.getPort());
dp2.setAddress(dp.getAddress());
ds.send(dp2);
ds.close();
} catch (SocketException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
客户端
package com.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient
{
public static void main(String[] args)
{
try
{
DatagramSocket ds=new DatagramSocket(9000);
System.out.println("客户端在 9000 监听");
String content="hello";
byte[] b=content.getBytes();
DatagramPacket dp=new DatagramPacket(b,0,b.length);
dp.setPort(9001);
dp.setAddress(InetAddress.getByName("192.168.2.102"));
ds.send(dp);
byte[] b2=new byte[1024];
DatagramPacket dp2=new DatagramPacket(b2,0,b2.length);
ds.receive(dp2);
byte[] data2=dp2.getData();
content=new String(data2,0,dp2.getLength());
System.out.println(content);
ds.close();
} catch (SocketException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}