Program Soket Java dengan GUI
03.16.001. Program Server
import java.io.*;
import java.net.*;
public class ProgramServer {
public static void main(String[]args){
try{
ServerSocket a=new ServerSocket(8000);
jta.append("Server dimulai pukul "+ new java.util.Date() + '\n');
Socket soket =a.accept();
DataInputStream masukanClient = new DataInputStream(
soket.getInputStream());
DataOutputStream keluaranDiClient = new DataOutputStream(
soket.getOutputStream());
while(true){
double jari2 = masukanClient.readDouble();
double luas = jari2 * jari2 * 22 / 7;
keluaranDiClient.writeDouble(luas);
jta.append("Jari-jari diterima dari client : " + jari2 + "\n");
jta.append("Luas nya : " + luas +"\n");
}
}catch(IOException ex){
System.err.println(ex);
}
}
}
2. Program Client
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 keServer;
private DataInputStream dariServer;
public static void main(String[]args){
new ProgramClient(); //manggil method
}
public ProgramClient(){ //method
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 soket = new Socket("localhost",8000);
dariServer = new DataInputStream(
soket.getInputStream());
keServer = new DataOutputStream(soket.getOutputStream());
}catch(IOException ex){
jta.append(ex.toString()+"\n");
}
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
double jari2 = Double.parseDouble(jtf.getText().trim());
keServer.writeDouble(jari2);
keServer.flush();
double luas = dariServer.readDouble();
jta.append("Radius is : "+jari2+"\n");
jta.append("Area received from the server : "+luas+"\n");
}catch(IOException ex){
System.err.println(ex);
}
}
}
}
4. Screenshoot Program :
0 komentar