Java Reference
In-Depth Information
59 }
60
catch
(IOException ex) {
61 System.err.println(ex);
62 }
63 });
64
65
try
{
66
// Create a socket to connect to the server
67
Socket socket =
new
Socket(
"localhost"
,
8000
);
request connection
68
// Socket socket = new Socket("130.254.204.36", 8000);
69
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
70
71
// Create an input stream to receive data from the server
72
fromServer =
new
DataInputStream(socket.getInputStream());
input from server
73
74
// Create an output stream to send data to the server
75
toServer =
new
DataOutputStream(socket.getOutputStream());
output to server
76 }
77
catch
(IOException ex) {
78 ta.appendText(ex.toString() +
'\n'
);
79 }
80 }
81 }
You start the server program first and then start the client program. In the client program, enter
a radius in the text field and press
Enter
to send the radius to the server. The server computes
the area and sends it back to the client. This process is repeated until one of the two programs
terminates.
The networking classes are in the package
java.net
. You should import this package
when writing Java network programs.
The
Server
class creates a
ServerSocket serverSocket
and attaches it to port 8000
using this statement (line 26 in Server.java):
ServerSocket serverSocket =
new
ServerSocket(
8000
);
The server then starts to listen for connection requests, using the following statement (line 31
in Server.java):
Socket socket = serverSocket.accept();
The server waits until the client requests a connection. After it is connected, the server reads
the radius from the client through an input stream, computes the area, and sends the result
to the client through an output stream. The
ServerSocket accept()
method takes time
to execute. It is not appropriate to run this method in the JavaFX application thread. So, we
place it in a separate thread (lines 23-59). The statements for updating GUI need to run from
the JavaFX application thread using the
Platform.runLater
method (lines 27-28, 49-53).
The
Client
class uses the following statement to create a socket that will request a con-
nection to the server on the same machine (localhost) at port 8000 (line 67 in Client.java).
Socket socket =
new
Socket(
"localhost"
,
8000
);
If you run the server and the client on different machines, replace
localhost
with the server
machine's host name or IP address. In this example, the server and the client are running on
the same machine.
If the server is not running, the client program terminates with a
java.net.ConnectException
. After it is connected, the client gets input and output
streams—wrapped by data input and output streams—in order to receive and send data to the
server.
Search WWH ::
Custom Search