1+ import java .io .*;
2+ import java .net .*;
3+ import java .util .Date ;
4+ import javafx .application .Application ;
5+ import javafx .application .Platform ;
6+ import javafx .scene .Scene ;
7+ import javafx .scene .control .TextArea ;
8+ import javafx .scene .control .ScrollPane ;
9+ import javafx .stage .Stage ;
10+
11+ public class Exercise31_04Server extends Application {
12+ // Text area for displaying contents
13+ private TextArea ta =new TextArea ();
14+
15+ // Count the thread
16+ private int threadNo =0 ;
17+
18+ @ Override // Override the start method in the Application class
19+ public void start (Stage primaryStage ) {
20+ // Create a scene and place it in the stage
21+ Scene scene =new Scene (new ScrollPane (ta ),450 ,200 );
22+ primaryStage .setTitle ("Exercise31_04Sever" );// Set the stage title
23+ primaryStage .setScene (scene );// Place the scene in the stage
24+ primaryStage .show ();// Display the stage
25+
26+ new Thread (() -> {
27+ try {
28+ // Create a server socket
29+ ServerSocket serverSocket =new ServerSocket (8000 );
30+ ta .appendText ("Exercise31_04Sever started at " +new Date () +'\n' );
31+
32+ while (true ) {
33+ // Listen for a new connection request
34+ Socket socket =serverSocket .accept ();
35+
36+ Platform .runLater (() -> {
37+ // Display the thread number
38+ ta .appendText ("Starting thread " +threadNo ++ +'\n' );
39+
40+ // Find the client's ip address
41+ InetAddress inetAddress =socket .getInetAddress ();
42+ ta .appendText ("Client IP /" +
43+ inetAddress .getHostAddress () +'\n' );
44+
45+ });
46+
47+ // Create and start new thread for the connection
48+ new Thread (new HandleAClient (socket )).start ();
49+ }
50+ }
51+ catch (IOException ex ) {
52+ System .err .println (ex );
53+ }
54+ }).start ();
55+ }
56+
57+ // Define the thread class for handlind new connection
58+ class HandleAClient implements Runnable {
59+ private Socket socket ;// A connected socket
60+
61+ /** Construct a thread */
62+ public HandleAClient (Socket socket ) {
63+ this .socket =socket ;
64+ }
65+
66+ /** Run a thread */
67+ public void run () {
68+ try {
69+ // Create a data output stream
70+ DataOutputStream outputToClient =new DataOutputStream (
71+ socket .getOutputStream ());
72+
73+ // Send a string to the Client
74+ outputToClient .writeUTF ("You are visitor " +threadNo );
75+ }
76+ catch (IOException ex ) {
77+ ex .printStackTrace ();
78+ }
79+ }
80+ }
81+ }