Laporan multiclient chatting berbasis grafis (gambar)

download

of 25

  • date post

    23-Jun-2015
  • Category

    Software
  • view

    126
  • download

    3

Embed Size (px)

transcript

  • 1. TUGAS Membuat Program MultiClient Chatting Client-Server Menggunakan Bahasa Pemrograman Java Berbasis Grafis Oleh : Rara Ariesta Priliani (061130701307) 6CD JURUSAN TEKNIK KOMPUTER POLITEKNIK NEGERI SRIWIJAYA PALEMBANG

2. Chatting memungkinkan kita untuk selalu bisa berkomunikasi walaupun kita tidak berada bersamanya di suatu tempat. Aplikasi chatting merupakan suatu aplikasi yang memungkinkan pengguna (client) berkomunikasi teks secara langsung (Real Time) dengan pengguna lain dengan menggunakan media yang ada. Java merupakan suatu bahasa pemograman yang multi platform dan multi device. Java juga merupakan bahasa pemograman yang berorientasi objek dan program java tersusun dari bagian yang disebut kelas. Pada bagian ini, saya akan membuat aplikasi chatting berbasis grafis (seperti tampilan foto) menggunakan bahasa pemograman java. pertama yang harus dilakukan adalah menyetting alamat IP pada masing-masing PC. Kita menggunakan satu server dan satu client. Pertama yang harus dilakukan kita terlebih dahulu melakukan setting alamat IP pada masing-masing client. Setelah melakukan konfigurasi IP pada masing-masingi komputer kemudian kita juga harus memastikan bahwa firewall pada masing-masing komputer harus diaktifkan karena pada beberapa kasus program ini tidak dapat saling terkoneksi akibat firewall yang aktif pada sistem operasinya. Berikut adalah listing program MultiClient Chatting Client-Server berbasis grafis (gambar) ChatServer.java import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static int uniqueId; private ArrayList clients; private int port; private boolean keepGoing; public ChatServer() { this.port = 9999; 3. clients = new ArrayList(); } public void start() { keepGoing = true; try { ServerSocket serverSocket = new ServerSocket(port); while (keepGoing) { System.out.println("ChatServer waiting for Clients on port " + port + "."); Socket socket = serverSocket.accept(); if (!keepGoing) { break; } ChatServer.ClientThread t = new ChatServer.ClientThread(socket); clients.add(t); t.start(); send("login~" + t.username + "~" + t.username + " sedang login...~Server~n"); } try { serverSocket.close(); for (int i = 0; i < clients.size(); ++i) { ChatServer.ClientThread tc = clients.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); 4. } catch (IOException ioE) { } } } catch (Exception e) { System.out.println("Exception closing the server and clients: " + e); } } catch (IOException e) { String msg = "Exception on new ServerSocket: " + e + "n"; System.out.println(msg); } } private synchronized void send(String message) { for (int i = clients.size(); --i >= 0;) { ChatServer.ClientThread ct = clients.get(i); if (!ct.writeMsg(message)) { clients.remove(i); System.out.println("Disconnected Client " + ct.username + " removed from list."); } } } private String getClients() { String s = ""; for (ClientThread clientThread : clients) { s += clientThread.username + ":"; 5. } s += "---"; System.out.println(s); return s; } private synchronized void remove(int id) { for (int i = 0; i < clients.size(); ++i) { ChatServer.ClientThread ct = clients.get(i); if (ct.id == id) { clients.remove(i); return; } } } public static void main(String[] args) { ChatServer server = new ChatServer(); server.start(); } private class ClientThread extends Thread { private Socket socket; private ObjectInputStream sInput; private ObjectOutputStream sOutput; private int id; private String username; 6. public ClientThread(Socket socket) { id = ++uniqueId; this.socket = socket; System.out.println("Menciptakan Object Input/Output Streams"); try { sOutput = new ObjectOutputStream(socket.getOutputStream()); sInput = new ObjectInputStream(socket.getInputStream()); String message = (String) sInput.readObject(); username = message.split("~")[1]; System.out.println(username + " masuk."); } catch (IOException e) { System.out.println("Exception creating new Input/output Streams: " + e); } catch (ClassNotFoundException e) { } } @Override public void run() { boolean keepGoing = true; while (keepGoing) { String message; try { message = sInput.readObject().toString(); } catch (IOException e) { 7. System.out.println(username + " Exception reading Streams: " + e); break; } catch (ClassNotFoundException e2) { break; } String type = message.split("~")[0]; String pengirim = message.split("~")[1]; String text = message.split("~")[2]; String kepada = message.split("~")[3]; String response; switch (type) { case "postText": response = "recieveText~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "postPrivateText": response = "recievePrivateText~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "login": response = "login~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "logout": 8. response = "logout~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "list": response = "list~server~" + getClients() + "~ ~ ~ ~ ~n"; send(response); break; } } remove(id); close(); } private void close() { try { if (sOutput != null) { sOutput.close(); } } catch (Exception e) { } try { if (sInput != null) { sInput.close(); } } catch (Exception e) { } 9. try { if (socket != null) { socket.close(); } } catch (Exception e) { } } private boolean writeMsg(String msg) { if (!socket.isConnected()) { close(); return false; } try { sOutput.writeObject(msg); } catch (IOException e) { System.out.println("Error sending message to " + username); System.out.println(e.toString()); } return true; } } } ChatClient.java import java.io.IOException; import java.io.ObjectInputStream; 10. import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.table.DefaultTableModel; public class ChatClient extends javax.swing.JFrame { /** * Creates new form ChatClient */ private ObjectInputStream input; private ObjectOutputStream output; private Socket socket; private String server, username; private int port; private List clients; public ChatClient() { clients = new ArrayList(); initComponents(); } 11. public boolean start() { try { socket = new Socket(server, port); } catch (Exception ec) { System.out.println("Error connectiong to server:" + ec); return false; } String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort(); System.out.println(msg); try { input = new ObjectInputStream(socket.getInputStream()); output = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException eIO) { System.out.println("Exception creating new Input/output Streams: " + eIO); return false; } new ChatClient.ListenFromServer().start(); try { output.writeObject("login~" + username + "~" + username + " sedang login...~server~n"); output.writeObject("list~" + username + "~" + username + " sedang login...~server~n"); 12. } catch (IOException eIO) { System.out.println("Exception doing login : " + eIO); disconnect(); return false; } return true; } private void disconnect() { try { // TODO add your handling code here: output.writeObject("logout~" + username + "~" + username + " sudah logout...~Server~n"); } catch (IOException ex) { //Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } try { if (input != null) { input.close(); } } catch (Exception e) { } try { if (output != null) { 13. output.close(); } } catch (Exception e) { } try { if (socket != null) { socket.close(); } } catch (Exception e) { } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); viewTextArea = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); clientTable = new javax.swing.JTable(); postTextField = new javax.swing.JTextField(); 14. kirimButton = new javax.swing.JButton(); lbljpg = new javax.swing.JLabel(new ImageIcon("E:/rara.jpg")); jLabel2 = new javax.swing.JLabel(); serverTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); portTextField = new javax.swing.JTextField(); masukButton = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); usernameTextField = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE ); viewTextArea.setEditable(false); viewTextArea.setColumns(20); viewTextArea.setLineWrap(true); viewTextArea.setRows(5); viewTextArea.setFocusable(false); jScrollPane1.setViewportView(viewTextArea); jScrollPane2.setViewportView(clientTable); postTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { postTextFieldActionPerformed(evt); } 15. }); kirimButton.setText("Kirim"); kirimButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kirimButtonActionPerformed(evt); } }); jLabel2.setText("Server"); serverTextField.setText("10.17.0.0"); jLabel3.setText("Port"); portTextField.setText("9999"); masukButton.setText("Masuk"); masukButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { masukButtonActionPerformed(evt); } }); jLabel4.setText("Username"); 16. usernameTextField.setText("Rara Ariesta"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayo