Java Reference
In-Depth Information
11
public class
MultiThreadServer
extends
Application {
12
// Text area for displaying contents
13
private
TextArea ta =
new
TextArea();
14
15
// Number a client
16
private int
clientNo =
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(
"MultiThreadServer"
);
// 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(
"MultiThreadServer started at "
31 +
new
Date() +
'\n'
);
32
33
server socket
while
(
true
) {
34
// Listen for a new connection request
connect client
35
Socket socket = serverSocket.accept();
36
37
// Increment clientNo
38 clientNo++;
39
40 Platform.runLater( () -> {
41
// Display the client number
42 ta.appendText(
"Starting thread for client "
+ clientNo +
43
update GUI
" at "
+
new
Date() +
'\n'
);
44
45
// Find the client's host name, and IP address
46 InetAddress inetAddress = socket.getInetAddress();
47 ta.appendText(
"Client "
+ clientNo +
"'s host name is "
48 + inetAddress.getHostName() +
"\n"
);
49 ta.appendText(
"Client "
+ clientNo +
"'s IP Address is "
50 + inetAddress.getHostAddress() +
"\n"
);
51 });
52
53
network information
// Create and start a new thread for the connection
54
new
Thread(
new
HandleAClient(socket)).start();
create task
55 }
56 }
57
catch
(IOException ex) {
58 System.err.println(ex);
59 }
60 }).start();
61 }
62
63
start thread
// Define the thread class for handling new connection
64
class
HandleAClient
implements
Runnable {
65
private
Socket socket;
// A connected socket
task class
66
67
/** Construct a thread */
68
public
HandleAClient(Socket socket) {
69
this
.socket = socket;
70 }
71
Search WWH ::
Custom Search