
Kali ini kita akan menambahkan fungsi di server java socket untuk menangani fungsi palindrome, age calculation, dan upper to lower char.
Kita langsung saja buka file server java socket lalu modifikasi fungsi run(), menjadi seperti dibawah ini:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public void run() { System.out.println(this.socket.getPort() + " working or sleeping for 5 seconds"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } DataInputStream clientinp; DataOutputStream clientout; try { clientinp = new DataInputStream(socket.getInputStream()); clientout = new DataOutputStream(socket.getOutputStream()); while (true) { System.out.println("reading..."); String sentence = clientinp.readUTF(); System.out.printf("read from socket %s: %s\n", this.socket.getPort(), sentence); if (sentence.equalsIgnoreCase("exit")) { System.out.printf("socket %s: to be down\n", this.socket.getPort()); clientout.writeUTF("bye"); break; } else if (sentence.contains("#calcAge")) { String[] data = sentence.split(":"); if (data.length < 3) { StringBuilder strBuilder = new StringBuilder(""); for (int i = 0; i < 4; i++) { strBuilder.append(calculateAgeOnPlanet(Double.valueOf(data[1]), i) + "\r\n"); } clientout.writeUTF(String.format("answer: %s", strBuilder.toString())); } else { clientout.writeUTF(String.format("answer: %s", calculateAgeOnPlanet(Double.valueOf(data[1]), Integer.valueOf(data[2])))); } } else if (sentence.contains("#palindrome")) { String[] data = sentence.split(":"); clientout.writeUTF(String.format("answer: %s", isPalindromeText(data[1]))); } else { clientout.writeUTF(String.format("answer: %s", getOrCaseString(sentence))); } } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } |
Semoga membantu,