最有名的UDP程式的例子,非DNS(Domain Name Server)莫屬了,假設每個電腦要詢問網址的主機IP位址都要透過TCP建連線的話,在資源使用上是很浪費的,而且IP位址的封包資料並沒有很大,因此就很適合利用UDP來實作。
底下為一個UDP Server/Client的範例,Client端輸入小寫英文字母,Server收到之後轉成大寫,再傳送回給Client端顯示在螢幕上。
udpServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class udpServer {
public static void main(String[] args) throws Exception{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
udpClient.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class udpClient {
public static void main(String[] args) throws Exception{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSetence = new String(receivePacket.getData());
System.out.println("FROM SERVER: "+modifiedSetence);
clientSocket.close();
}
}
Server端執行結果
Client端執行結果
沒有留言:
張貼留言