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.

71 lines
1.8 KiB

  1. package xyz.nextn;
  2. import java.io.BufferedInputStream;
  3. import java.io.DataInputStream;
  4. import java.io.IOException;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. public class Server {
  8. protected int serverPort = 1111;
  9. protected ServerSocket serverSocket = null;
  10. protected boolean isStopped = false;
  11. protected Thread runningThread= null;
  12. public Server(int port){
  13. this.serverPort = port;
  14. }
  15. public void run(){
  16. synchronized(this){
  17. this.runningThread = Thread.currentThread();
  18. }
  19. openServerSocket();
  20. while(! isStopped()){
  21. Socket clientSocket = null;
  22. try {
  23. clientSocket = this.serverSocket.accept();
  24. } catch (IOException e) {
  25. if(isStopped()) {
  26. System.out.println("Server Stopped.") ;
  27. return;
  28. }
  29. throw new RuntimeException(
  30. "Error accepting client connection", e);
  31. }
  32. new Thread(
  33. new WorkerRunnable(
  34. clientSocket, "Multithreaded Server")
  35. ).start();
  36. }
  37. System.out.println("Server Stopped.") ;
  38. }
  39. private synchronized boolean isStopped() {
  40. return this.isStopped;
  41. }
  42. public synchronized void stop(){
  43. this.isStopped = true;
  44. try {
  45. this.serverSocket.close();
  46. } catch (IOException e) {
  47. throw new RuntimeException("Error closing server", e);
  48. }
  49. }
  50. private void openServerSocket() {
  51. try {
  52. this.serverSocket = new ServerSocket(this.serverPort);
  53. } catch (IOException e) {
  54. throw new RuntimeException("Cannot open port 8080", e);
  55. }
  56. }
  57. }