Guest User

Server Class

a guest
Oct 14th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.net.*;
  4. import java.util.Date;
  5.  
  6. public class Server {
  7.  
  8. private ServerSocket serverSocket;
  9. private Socket clientEnd;
  10.  
  11. private int port;
  12.  
  13. public Server(int port) {
  14.  
  15. this.setPort(port);
  16.  
  17. Thread server = new Thread(() -> {
  18. try {
  19. Runtime.getRuntime().addShutdownHook(new Thread(){public void run(){
  20. try {
  21. serverSocket.close();
  22. System.out.println("The server is shut down!");
  23. } catch (IOException e) { /* failed */ }
  24. }});
  25. serverSocket = new ServerSocket(port);
  26. serverSocket.setReuseAddress(true);
  27.  
  28. clientEnd = serverSocket.accept();
  29.  
  30. try (DataInputStream dataIn = new DataInputStream(clientEnd.getInputStream());
  31. DataOutputStream dataOut = new DataOutputStream(clientEnd.getOutputStream());) {
  32.  
  33. while (true) {
  34.  
  35. String message = dataIn.readUTF();
  36. if (message.matches("[Ee]xit"))
  37. break;
  38. message = "on " + new Date() + " , the Server Received " + message;
  39.  
  40. dataOut.writeUTF(message);
  41. dataOut.flush();
  42.  
  43.  
  44. }
  45.  
  46. }
  47.  
  48. } catch (IOException e) {
  49.  
  50. e.printStackTrace();
  51. }
  52. finally {
  53. try {
  54. serverSocket.close();
  55. } catch (IOException e) {
  56.  
  57. e.printStackTrace();
  58. }
  59. }
  60. });
  61. server.start();
  62.  
  63. }
  64.  
  65. public int getPort() {
  66. return port;
  67. }
  68.  
  69. public void setPort(int port) {
  70. this.port = port;
  71. }
  72.  
  73. public static void main(String[] args) throws IOException {
  74.  
  75.  
  76. Server server = new Server(8020);
  77. Client local = new Client("localhost", 8020);
  78.  
  79. }
  80.  
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment