Topshiriq:
Talabalar 2.1-jadvalda keltirilgan o‘zlariga belgilangan variantlarni olib UDP kliyent-server tarmoq dasturini yaratishadi.
1labaratoriya
package Lab2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
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);
}
}
}
package Lab2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
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];
Scanner scanner = new Scanner(System.in);
System.out.print("Sonlar miqdorini kiriting: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println(n + " ta sonni kiriting:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
if (numbers[i] > 0) {
sum += numbers[i];
}
}
String sentence = String.valueOf(sum);
sendData = sentence.getBytes();
System.out.println("Serverga yuborildi");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, sendData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("Serverdan qaytgan javob :" + modifiedSentence);
clientSocket.close();
}
}
|