You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2 KiB

  1. package xyz.nextn;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. public class Server {
  9. private ServerSocket serverSocket;
  10. public void start(int port){
  11. try {
  12. serverSocket = new ServerSocket(port);
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. while (true) {
  17. try {
  18. new EchoClientHandler(serverSocket.accept()).start();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. public void stop() throws IOException {
  25. serverSocket.close();
  26. }
  27. private static class EchoClientHandler extends Thread {
  28. private Socket clientSocket;
  29. private PrintWriter out;
  30. private BufferedReader in;
  31. public EchoClientHandler(Socket socket) {
  32. this.clientSocket = socket;
  33. }
  34. public void run() {
  35. try {
  36. out = new PrintWriter(clientSocket.getOutputStream(), true);
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. try {
  41. in = new BufferedReader(
  42. new InputStreamReader(clientSocket.getInputStream()));
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. String inputLine = null;
  47. while (true) {
  48. try {
  49. if (!((inputLine = in.readLine()) != null)) break;
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. if (".".equals(inputLine)) {
  54. out.println("bye");
  55. break;
  56. }
  57. out.println(inputLine);
  58. }
  59. try {
  60. in.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. out.close();
  65. try {
  66. clientSocket.close();
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. }
  72. }