//服務(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ù)報(bào)包用來(lái)實(shí)現(xiàn)無(wú)連接包投遞服務(wù)
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//數(shù)據(jù)報(bào)套接字是包投遞服務(wù)的發(fā)送或接收點(diǎn)
DatagramSocket ds = new DatagramSocket(8888);
while(true)
{
//從此套接字接收數(shù)據(jù)報(bào)包
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
{
//定義一個(gè)Long類(lèi)型的數(shù)據(jù)
long n= 10000L;
//聲明一個(gè)輸出管道
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//數(shù)據(jù)輸出流允許應(yīng)用程序以適當(dāng)方式將基本 Java 數(shù)據(jù)類(lèi)型寫(xiě)入輸出流中
DataOutputStream dos = new DataOutputStream(baos);
//將一個(gè) long 值以 8-byte 值形式寫(xiě)入基礎(chǔ)輸出流中,先寫(xiě)入高字節(jié)。如果沒(méi)有拋出異常,則計(jì)數(shù)器 written 增加 8。
dos.writeLong(n);
//創(chuàng)建一個(gè)新分配的 byte 數(shù)組。其大小是此輸出流的當(dāng)前大小,并且緩沖區(qū)的有效內(nèi)容已復(fù)制到該數(shù)組中。
byte[] buf = baos.toByteArray();1
//構(gòu)造數(shù)據(jù)報(bào)包,用來(lái)將長(zhǎng)度為 length 的包發(fā)送到指定主機(jī)上的指定端口號(hào)。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ù)報(bào)包
ds.send(dp);
//關(guān)閉此數(shù)據(jù)報(bào)套接字
ds.close();
}
}
posted on 2009-05-17 09:29
Werther 閱讀(312)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
10.Java