SortClientServer

This commit is contained in:
Ece Nur Keles 2023-12-05 16:32:59 +01:00
parent 7feec0d3cd
commit 6114fcb1ab
2 changed files with 114 additions and 0 deletions

View File

@ -0,0 +1,54 @@
package praktikum04;
import javax.sound.sampled.Port;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SorterClient {
public static void main(String[] args) {
SorterClient client = new SorterClient();
client.run();
}
private void run() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty())
break;
line = sort(line);
System.out.println(line);
}
scanner.close();
}
private String sort(String line) {
InetSocketAddress address =
new InetSocketAddress("localhost", 12345);
try (Socket socket = new Socket()) {
socket.connect(address);
sendLine(socket, line);
String answer = receiveLine(socket);
return answer;
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return "*";
}
public static void sendLine(Socket socket, String line) throws IOException {
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(line);
writer.flush();
}
public static String receiveLine(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
return reader.readLine();
}
}

View File

@ -0,0 +1,60 @@
package praktikum04;
import java.io.*;
import java.net.*;
import java.util.Arrays;
public class SorterServer implements Runnable {
public static void main(String[] args) {
final int port = 12345;
try (ServerSocket socket = new ServerSocket(port)) {
while (true) {
Socket client = socket.accept();
Thread thread = new Thread(new SorterServer(client));
thread.start();
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
Socket client;
private SorterServer(Socket client) {
this.client = client;
}
public void run() {
try {
String line = receiveLine(client);
char[] chars = line.toCharArray();
Arrays.sort(chars);
String answer = new String(chars);
sendLine(client, answer);
System.out.println(line + " -> " + answer);
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
finally {
try { client.close(); } catch (Exception e) {}
}
}
public static void sendLine(Socket socket, String line) throws IOException {
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(line);
writer.flush();
}
public static String receiveLine(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
return reader.readLine();
}
}