Untitled
unknown
plain_text
2 years ago
3.2 kB
3
Indexable
package socketthreading_server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class SocketThreading_Server { public static void main(String[] args) throws IOException { ServerSocket serverHandshake = new ServerSocket(5567); System.out.println("Server's Handshaking Port: " + " serverHandshake.getLocalPort() "); System.out.println("\n Server is UP! " + "Waiting for Clients..."); while (true) { Socket serverCommunication = serverHandshake.accept(); System.out.println("\n New Client Connected to the Server!" + " "); System.out.println("\n Assigning Thread for" + " " + serverCommunication + "... "); DataOutputStream output = new DataOutputStream(serverCommunication.getOutputStream()); DataInputStream input = new DataInputStream(serverCommunication.getInputStream()); Thread newTunnel = new SocketTheading_clientHandler(serverCommunication, input, output); newTunnel.start(); } } private static class SocketTheading_clientHandler extends Thread { DateFormat forDate = new SimpleDateFormat("yyyy/MM/dd"); DateFormat forTime = new SimpleDateFormat("hh:mm:ss"); final Socket communicationTunnel; // for input-output final DataInputStream inputTunnel; final DataOutputStream outputTunnel; String received = ""; String toReturn = ""; public SocketTheading_clientHandler(Socket serverCommunication, DataInputStream input, DataOutputStream output) { this.communicationTunnel=serverCommunication; this.inputTunnel=input; this.outputTunnel=output; } @Override public void run() { while (true) { try { outputTunnel.writeUTF("\n What do You Want?[38;1;3;5m[date | time | exit] \033[0m\033[35;1m: \033[0m"); received = inputTunnel.readUTF(); if (received.equals("exit")) { System.out.println("\n Client requested for Closing the Connection!"); this.communicationTunnel.close(); System.out.println("Connection closed with " + this.communicationTunnel + "... "); break; } Date date = new Date(); switch (received) { case "date": toReturn = "Date: " + " " + forDate.format(date) + " "; outputTunnel.writeUTF(toReturn); break; case "time": toReturn = " Time: " + " " + forTime.format(date) + " "; outputTunnel.writeUTF(toReturn); break; default: toReturn = "Invalid Input!, Try again... "; outputTunnel.writeUTF(toReturn); } } catch (IOException exception) { //System.out.println(exception); } } try { this.outputTunnel.close(); this.inputTunnel.close(); } catch (IOException exception) { //System.out.println(exception); } } } }
Editor is loading...