-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathServer.java
More file actions
57 lines (46 loc) · 1.52 KB
/
Server.java
File metadata and controls
57 lines (46 loc) · 1.52 KB
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
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame {
// Text area for displaying contents
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new Server();
}
public Server() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area found: " + area + '\n');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
}