Pada kesempatan kali ini, saya akan membagi tutorial pembuatan aplikasi Java. Yakni Aplikasi Socket Server dan Client. Aplikasi ini saya buat dengan menggunakan IDE Netbeans IDE 7.2 Adapun aplikasi yang dibuat adalah aplikasi Chatting. Nah, aplikasi ini dibuat dalam satu form. Untuk pemilihan server dan client nantinya akan dipilih melalui Combobox. Untuk komunikasi IP address, aplikasi ini menggunakan IP Localhost (127.0.0.1).

Nah, bagaimana cara pembuatan hingga test applikasi, simak video tutorial pembuatan aplikasi berikut.

Dan berikut source code Chatting Application.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socketserver_client;

import com.sun.org.apache.xpath.internal.operations.Equals;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import sun.awt.windows.ThemeReader;

/**
 *
 * @author Eidelbert
 */
public class Socket_Chat extends javax.swing.JFrame implements Runnable {

Socket client;
 ServerSocket server;
 BufferedReader Server_Reader, Client_BefferedReader;
 BufferedWriter Server_Writer, Client_Writer;

/**
 * Creates new form Socket_Chat
 */
 public Socket_Chat() {
 initComponents();
 }

/**
 * 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 client_connection() {
 try {
 String ip = JOptionPane.showInputDialog("Masukkan IP Address!");
 client = new Socket(ip, 2000);
 Combo_Box.setEnabled(false);
 Button_On.setText("Disconnect");
 Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
 Server_Writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
 } catch (UnknownHostException ex) {
 System.out.println("Accept Failed");
 System.exit(-1);
 } catch (IOException ex) {
 Logger.getLogger(Socket_Chat.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

private void read_connection() {
 try {
 try {
 try {
 server = new ServerSocket(2000);
 this.setTitle("Please Wait...");
 } catch (IOException ex) {
 System.out.println("Could not listen");
 System.exit(-1);
 }
 client = server.accept();
 this.setTitle("Connected" + client.getInetAddress());
 } catch (IOException ex) {
 System.out.println("Accept Failed");
 System.exit(-1);
 }

Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
 Server_Writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
 } catch (IOException ex) {
 System.out.println("Read Failed");
 System.exit(-1);
 }

}

private void disconnected_by_client() {
 try {
 client.close();
 Server_Reader.close();
 Server_Writer.close();
 Combo_Box.setEnabled(true);
 Button_On.setText("Connect");
 } catch (IOException ex) {
 Logger.getLogger(Socket_Chat.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

private void stopped_by_server() {
 try {
 Server_Reader.close();
 Server_Writer.close();
 Button_On.setText("On");
 this.setTitle("Disconnected");
 } catch (IOException ex) {
 Logger.getLogger(Socket_Chat.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

// <editor-fold defaultstate="collapsed" desc="Generated Code">
 private void initComponents() {

Combo_Box = new javax.swing.JComboBox();
 Button_On = new javax.swing.JButton();
 List_Chat = new java.awt.List();
 Button_Send = new javax.swing.JButton();
 Label_Username = new javax.swing.JLabel();
 Text_Username = new javax.swing.JTextField();
 Text_Chat = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

Combo_Box.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Server", "Client" }));
 Combo_Box.addItemListener(new java.awt.event.ItemListener() {
 public void itemStateChanged(java.awt.event.ItemEvent evt) {
 Combo_BoxItemStateChanged(evt);
 }
 });

Button_On.setText("ON");
 Button_On.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 Button_OnActionPerformed(evt);
 }
 });

Button_Send.setText("Kirim");
 Button_Send.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
 Button_SendActionPerformed(evt);
 }
 });

Label_Username.setText("Your Name");

Text_Username.setText("Server");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
 getContentPane().setLayout(layout);
 layout.setHorizontalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addComponent(Button_Send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
 .addComponent(Text_Chat)
 .addComponent(List_Chat, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
 .addGap(0, 55, Short.MAX_VALUE)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addComponent(Label_Username)
 .addGap(18, 18, 18)
 .addComponent(Text_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
 .addGroup(layout.createSequentialGroup()
 .addComponent(Combo_Box, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addGap(18, 18, 18)
 .addComponent(Button_On)))))
 .addContainerGap())
 );
 layout.setVerticalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 .addGroup(layout.createSequentialGroup()
 .addContainerGap()
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(Combo_Box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addComponent(Button_On))
 .addGap(5, 5, 5)
 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
 .addComponent(Text_Username, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addComponent(Label_Username))
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(List_Chat, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
 .addComponent(Text_Chat, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
 .addGap(18, 18, 18)
 .addComponent(Button_Send)
 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
 );

pack();
 }// </editor-fold>

private void Combo_BoxItemStateChanged(java.awt.event.ItemEvent evt) {
 if (Combo_Box.getSelectedItem().equals("Server")) {
 Button_On.setText("On");
 Text_Username.setText("Server");
 } else {
 Button_On.setText("Connect");
 Text_Username.setText("Client");
 }

}

private void Button_OnActionPerformed(java.awt.event.ActionEvent evt) {
 if (Button_On.getText().equals("Connect")) {
 Button_On.setText("Disconnect");
 client_connection();

Thread thread = new Thread(this);
 thread.start();

} else if (Combo_Box.getSelectedItem().equals("Server")) {
 Button_On.setText("off");
 read_connection();

Thread thread = new Thread(this);
 thread.start();
 } else if (Button_On.getText().equals("Disconnect")) {
 disconnected_by_client();
 } else if (Button_On.getText().equals("Off")) {
 stopped_by_server();
 }
 // TODO add your handling code here:
 }

private void Button_SendActionPerformed(java.awt.event.ActionEvent evt) {

try {
 Server_Writer.write(Text_Username.getText() + ": " + Text_Chat.getText());
 Server_Writer.newLine();
 Server_Writer.flush();
 } catch (IOException ex) {
 Logger.getLogger(Socket_Chat.class.getName()).log(Level.SEVERE, null, ex);
 }
 List_Chat.add("me: " + Text_Chat.getText());
 Text_Chat.setText("");

}

/**
 * @param args the command line arguments
 */
 public static void main(String args[]) {
 /* Set the Nimbus look and feel */
 //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
 /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
 */
 try {
 for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
 if ("Nimbus".equals(info.getName())) {
 javax.swing.UIManager.setLookAndFeel(info.getClassName());
 break;
 }
 }
 } catch (ClassNotFoundException ex) {
 java.util.logging.Logger.getLogger(Socket_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (InstantiationException ex) {
 java.util.logging.Logger.getLogger(Socket_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (IllegalAccessException ex) {
 java.util.logging.Logger.getLogger(Socket_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 } catch (javax.swing.UnsupportedLookAndFeelException ex) {
 java.util.logging.Logger.getLogger(Socket_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 }
 //</editor-fold>

/* Create and display the form */
 java.awt.EventQueue.invokeLater(new Runnable() {
 public void run() {
 new Socket_Chat().setVisible(true);
 }
 });
 }
 // Variables declaration - do not modify
 private javax.swing.JButton Button_On;
 private javax.swing.JButton Button_Send;
 private javax.swing.JComboBox Combo_Box;
 private javax.swing.JLabel Label_Username;
 private java.awt.List List_Chat;
 private javax.swing.JTextField Text_Chat;
 private javax.swing.JTextField Text_Username;
 // End of variables declaration

public void run() {
 while (true) {
 try {
 List_Chat.add(Server_Reader.readLine());
 } catch (IOException ex) {
 Logger.getLogger(Socket_Chat.class.getName()).log(Level.SEVERE, null, ex);
 }
 }
 }
}

Cukup sekian yang dapat saya bagikan untuk tutorial kali ini. Terimakasih…🙂