好站連結:程式設計工藝大師
---------------------------------
姓名:劉宜妮
學號:9930083
---------------------------------
..作業三..
程式碼:
<<Client端>>
//Client
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame implements ActionListener {
private JTextField JexT = new JTextField();
private JTextArea JtaR = new JTextArea();
DataOutputStream osTS;
DataInputStream iFrS;
public static void main(String[] args) {
new Client();
}
public Client() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter Random Number"), BorderLayout.WEST);
p.add(JexT, BorderLayout.CENTER);
JexT.setHorizontalAlignment(JTextField.RIGHT);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p, BorderLayout.SOUTH);
getContentPane().add(new JScrollPane(JtaR), BorderLayout.CENTER);
JexT.addActionListener(this);
setSize(500,300);
setTitle("Client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try {
Socket connectToServer = new Socket("localhost", 7000);
iFrS = new DataInputStream(
connectToServer.getInputStream());
osTS =
new DataOutputStream(connectToServer.getOutputStream());
}
catch (IOException ex) {
JtaR.append(ex.toString() + '\n');
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JTextField) {
try {
double radius = Double.parseDouble(JexT.getText().trim());
osTS.writeDouble(radius);
osTS.flush();
double area = iFrS.readDouble();
JtaR.append("劉宜妮 is " + radius + "\n");
JtaR.append("Random Number received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
<<Server端>>
//Server
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame {
private JTextArea JtaR = new JTextArea();
public static void main(String[] args) {
new Server();
}
public Server() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new JScrollPane(JtaR), BorderLayout.CENTER);
setSize(450, 300);
setTitle("Server");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try {
ServerSocket Sersock= new ServerSocket(7000);
JtaR.append("Server started at " + new Date() + '\n');
Socket ConTe = Sersock.accept();
DataInputStream disFC = new DataInputStream(
ConTe.getInputStream());
DataOutputStream dosTC = new DataOutputStream(
ConTe.getOutputStream());
while (true) {
double Numb = disFC.readDouble();
double Aex = Numb*Numb*Math.random();
dosTC.writeDouble(Aex);
JtaR.append("Number received from client: " + Numb + '\n');
JtaR.append("Random number is : " + Aex + '\n');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
}
結果畫面:
留言列表