-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathClient.java
83 lines (68 loc) · 2.32 KB
/
Client.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame {
// Text field for receiving radius
private JTextField jtf = new JTextField();
// Text area to display contents
private JTextArea jta = new JTextArea();
// IO streams
private DataOutputStream toServer;
private DataInputStream fromServer;
public static void main(String[] args) {
new Client();
}
public Client() {
// Panel p to hold the label and text field
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setHorizontalAlignment(JTextField.RIGHT);
setLayout(new BorderLayout());
add(p, BorderLayout.NORTH);
add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(new ButtonListener()); // Register listener
setTitle("Client");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Socket socket = new Socket("130.254.204.36", 8000);
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(
socket.getInputStream());
// Create an output stream to send data to the server
toServer =
new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
jta.append(ex.toString() + '\n');
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
// Get the radius from the text field
double radius = Double.parseDouble(jtf.getText().trim());
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble();
// Display to the text area
jta.append("Radius is " + radius + "\n");
jta.append("Area received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}