Write a client-server program using TCP or UDP where the client sends 10 numbers and server responds with the numbers in sorted order.
TCP Client:
import java.io.*;
import java.net.*;
import java.util.*;
class ClientNumberSorted {
public static void main(String[] args) {
try {
Socket socket = new Socket("Localhost", 9874);
Scanner sc = new Scanner(System.in);
InputStream recNum = socket.getInputStream();
OutputStream sndNum = socket.getOutputStream();
DataInputStream inputNum = new DataInputStream(recNum);
DataOutputStream outputNum = new DataOutputStream(sndNum);
System.out.println("Enter number for sorting: ");
for(int i=0; i<10; i++) {
System.out.print("Enter number " + i + ": ");
int n = sc.nextInt();
outputNum.writeInt(n);
}
System.out.println("Sorted array: ");
for(int i=0; i<10; i++) {
System.out.println(inputNum.readInt());
}
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
TCP Server:
import java.io.*;
import java.net.*;
import java.util.*;
class ServerNumberSorted {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9874);
Socket socket = serverSocket.accept();
Scanner sc = new Scanner(System.in);
InputStream recNum = socket.getInputStream();
OutputStream sndNum = socket.getOutputStream();
DataInputStream inputNum = new DataInputStream(recNum);
DataOutputStream outputNum = new DataOutputStream(sndNum);
int array[] = new int[10];
for(int i=0; i<10; i++) {
array[i] = inputNum.readInt();
}
Arrays.sort(array);
for(int i=0; i<10; i++) {
outputNum.writeInt(array[i]);
}
socket.close();
serverSocket.close();
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
0 Comments