Advertisement
Guest User

serv

a guest
May 15th, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4.  
  5. import javafx.application.Application;
  6. import javafx.application.Platform;
  7. import javafx.scene.Scene;
  8. import javafx.scene.control.ScrollPane;
  9. import javafx.scene.control.TextArea;
  10. import javafx.stage.Stage;
  11.  
  12. public class Server extends Application {
  13.  
  14. private int clientNo = 0;
  15. private TextArea ta = new TextArea();
  16.  
  17. @Override
  18. public void start (Stage primaryStage) throws Exception {
  19. ta.setEditable(false);
  20.  
  21. Scene scene = new Scene(new ScrollPane(ta), 450, 200);
  22. primaryStage.setScene(scene);
  23. primaryStage.setTitle("Server");
  24. primaryStage.show();
  25.  
  26. new Thread( () -> {
  27. try {
  28. ServerSocket serverSocket = new ServerSocket(8182);
  29.  
  30. Platform.runLater( () -> {
  31. ta.appendText("Server started time " + new Date() + '\n');
  32. });
  33.  
  34. while (true) {
  35. Socket socket = serverSocket.accept();
  36. clientNo++;
  37.  
  38. Platform.runLater( () -> {
  39. ta.appendText("Starting client " + clientNo + " at " + new Date() + '\n');
  40. ta.appendText("Client " + clientNo + " IP Address is " + socket.getInetAddress().getHostAddress() + '\n');
  41. });
  42.  
  43. new Thread(new ThreadClient(socket)).start();
  44. }
  45. } catch (Exception e) {
  46. ta.appendText(e.toString() + '\n');
  47. }
  48. }).start();
  49. }
  50.  
  51. class ThreadClient implements Runnable {
  52.  
  53. private Socket socket;
  54.  
  55. public ThreadClient(Socket socket) {
  56. this.socket = socket;
  57. }
  58.  
  59. @Override
  60. public void run () {
  61. try {
  62. DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
  63. DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
  64.  
  65. while (true) {
  66. int normal = inputFromClient.readInt();
  67. int inverse = normal;
  68.  
  69. outputToClient.write(inverse);
  70.  
  71. Platform.runLater( () -> {
  72. ta.appendText("Text received from client: " + normal + '\n');
  73. ta.appendText("Inverse is " + inverse + '\n');
  74. });
  75. }
  76. } catch (Exception e) {
  77. ta.appendText(e.toString() + '\n');
  78. }
  79. }
  80. }
  81.  
  82.  
  83. public static void main (String[] args) {
  84. Application.launch(args);
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement