Java UDP網路編程主要通過 DatagramSocket和DatagramPacket 兩個類實現的,下面是一個樣本程式,
Server監聽UDP 2000連接埠並把收到的Long類型數值列印出來
Client則通過輸入獲得Long類型的數值,並把它發給Server
Server: /**/ /* Coding by nyzhl */
import java.net. * ;
import java.io. * ;
public class DatagramServer ... {
public static void main (String[] args) ...{
DatagramSocket ds = null;
try ...{
ds = new DatagramSocket(2000);
}
catch (SocketException e) ...{
e.printStackTrace();
System.exit(-1);
}
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
while (true) ...{
DataInputStream in = new DataInputStream (
new ByteArrayInputStream (buffer)
);
try ...{
ds.receive(dp);
System.out.println(in.readLong());
in.close();
}
catch (IOException e) ...{
e.printStackTrace();
continue;
}
}
//ds.close(); JDK提示"無法訪問的語句"
//因為前面是死迴圈,無論如何也執行不到後面的語句
}
}
Client: /**/ /* coding by nyzhl */
import java.net. * ;
import java.io. * ;
public class DatagramClient ... {
public static void main (String[] args) ...{
DatagramSocket ds = null;
try ...{
ds = new DatagramSocket();
}
catch (SocketException e) ...{
e.printStackTrace();
System.exit(-1);
}
BufferedReader typeReader = new BufferedReader (
new InputStreamReader(System.in)
);
long data = 0;
while(true) ...{
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream (bytesOut);
try ...{
data =<