1 回答
TA贡献1829条经验 获得超7个赞
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame
{
private JTextArea jta=new JTextArea();
public static void main(String[] args)
{ new Server(); }
public Server()
{
setLayout(new BorderLayout());
add(new JScrollPane(jta),BorderLayout.CENTER);
setTitle("Server");
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try
{
ServerSocket serverSocket=new ServerSocket(8000);
jta.append("Server started at "+new Date()+'\n');
Socket socket=serverSocket.accept();
DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());
while(true)
{
double radius=inputFromClient.readDouble();
double area=radius*radius*Math.PI;
outputToClient.writeDouble(area);
jta.append("Radius received from client: "+radius+'\n');
jta.append("Area found: "+area+'\n');
}
}
catch(IOException ex)
{ System.err.println(ex); }
}
}
客户端代码如下:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame
{
private JTextField jtf=new JTextField();
private JTextArea jta=new JTextArea();
private DataOutputStream toServer;
private DataInputStream fromServer;
public static void main(String args[])
{
new Client();
}
public Client()
{
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());
setTitle("Client");
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try
{
Socket socket=new Socket("dzy_3347ff08bc0.whpu.edu.cn",8000);
fromServer=new DataInputStream(socket.getInputStream());
toServer=new DataOutputStream(socket.getOutputStream());
}
catch(IOException ex)
{ System.out.println(ex); }
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
double radius=Double.parseDouble(jtf.getText().trim());
toServer.writeDouble(radius);
toServer.flush();
double area=fromServer.readDouble();
jta.append("Radius is "+radius+"\n");
jta.append("Area received from the server is "+area+'\n');
}
catch(IOException ex)
{ System.out.println(ex); }
}
}
}
添加回答
举报