//服務(wù)器端
import java.net.*;
import java.io.*;
public class TestUDPServer{
public static void main(String args[])throws Exception
{
byte buf[]= new byte[1024];
//數(shù)據(jù)報包用來實現(xiàn)無連接包投遞服務(wù)
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//數(shù)據(jù)報套接字是包投遞服務(wù)的發(fā)送或接收點
DatagramSocket ds = new DatagramSocket(8888);
while(true)
{
//從此套接字接收數(shù)據(jù)報包
ds.receive(dp);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
DataInputStream dis = new DataInputStream(bais);
//從包含的輸入流中讀取此操作需要的字節(jié)
System.out.println(dis.readLong());
}
}
}
//客戶端
import java.net.*;
import java.io.*;
public class TestUDPClient
{
public static void main(String args[])throws Exception
{
//定義一個Long類型的數(shù)據(jù)
long n= 10000L;
//聲明一個輸出管道
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//數(shù)據(jù)輸出流允許應(yīng)用程序以適當(dāng)方式將基本 Java 數(shù)據(jù)類型寫入輸出流中
DataOutputStream dos = new DataOutputStream(baos);
//將一個 long 值以 8-byte 值形式寫入基礎(chǔ)輸出流中,先寫入高字節(jié)。如果沒有拋出異常,則計數(shù)器 written 增加 8。
dos.writeLong(n);
//創(chuàng)建一個新分配的 byte 數(shù)組。其大小是此輸出流的當(dāng)前大小,并且緩沖區(qū)的有效內(nèi)容已復(fù)制到該數(shù)組中。
byte[] buf = baos.toByteArray();1
//構(gòu)造數(shù)據(jù)報包,用來將長度為 length 的包發(fā)送到指定主機(jī)上的指定端口號。length 參數(shù)必須小于等于 buf.length。
DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",8888));
DatagramSocket ds = new DatagramSocket(6666);
//從此套接字發(fā)送數(shù)據(jù)報包
ds.send(dp);
//關(guān)閉此數(shù)據(jù)報套接字
ds.close();
}
}