−
address: datagramma yuboriladigan adresni beradi;
−
port: masofadagi kompyuter datagrammani qabul qilishda ishlatadigan port
nomerini beradi.
DatagramSocket klassining send() metodi adresga DatagramPacket obyektini
yuboradi.
UDP serverini ishga tushirish uchun main() metodidagi konstruktor klassi
chaqiriladi.
Quyida UDP serverning Java kodi keltirilgan:
package udp;
import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
System.out.println("Server ishga tushdi!");
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("Qabul qilindi: " + sentence);
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);
}
}
}
UDP kliyentini yaratish. UDP kliyenti UDP protokolidan serverga so‘rovlarni
yuborish va server ilovasidan javoblarni qabul qilish uchun
foydalanadigan ilovadir.
Foydalanuvchining UDP-ilovasida UDP serveridan xabarlarni qabul qiladigan
DatagramSocket klass obyektini yaratish zarur, bu uchun esa quyidagilarni bajarish
lozim bo‘ladi:
1. Server bilan ulanish o‘rnatish uchun DatagramSocket klass obyektidan
foydalanuvchi soketini yaratish.
2. DatagramPacket klass obyektini yaratish va xabarlarni serverga yuborish
uchun send() metodidan foydalanish.
3. DatagramPacket klass obyektini yaratish va serverdan yuborilgan
xabarlarni qabul qilish uchun receive() metodidan foydalanish.
DatagramSocket obyekti so‘rov yuboriladigan serverning IP-manzili va port
raqamini o‘z ichiga oladi.
Quyida UDP kliyentning Java kodi keltirilgan:
package udp;
import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[]) throws Exception
{
System.out.println("Client ishga tushdi!");
BufferedReader
inFromUser
=
new
BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
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 modifiedSentence = new String(receivePacket.getData());
System.out.println("SERVERDAN:" + modifiedSentence);
clientSocket.close();
}
}