Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- /**
- *
- * @author Evgeniy Osipov http://fastandclever.ru/
- * @version 1.0
- */
- public class JLChat extends javax.swing.JFrame {
- /**
- * Creates new form JLChat
- */
- public JLChat() {
- 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")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">
- private void initComponents() {
- buttonGroup1 = new javax.swing.ButtonGroup();
- jTextField1 = new javax.swing.JTextField();
- jLabel1 = new javax.swing.JLabel();
- jTextField2 = new javax.swing.JTextField();
- jLabel2 = new javax.swing.JLabel();
- jTextField3 = new javax.swing.JTextField();
- jLabel3 = new javax.swing.JLabel();
- jScrollPane1 = new javax.swing.JScrollPane();
- jTextArea1 = new javax.swing.JTextArea();
- jButton3 = new javax.swing.JButton();
- jScrollPane2 = new javax.swing.JScrollPane();
- jTextArea2 = new javax.swing.JTextArea();
- jScrollPane3 = new javax.swing.JScrollPane();
- jTextArea3 = new javax.swing.JTextArea();
- jRadioButton1 = new javax.swing.JRadioButton();
- jRadioButton2 = new javax.swing.JRadioButton();
- jLabel4 = new javax.swing.JLabel();
- jButton1 = new javax.swing.JButton();
- jButton2 = new javax.swing.JButton();
- jMenuBar1 = new javax.swing.JMenuBar();
- jMenu1 = new javax.swing.JMenu();
- jMenuItem1 = new javax.swing.JMenuItem();
- jMenu2 = new javax.swing.JMenu();
- jMenuItem3 = new javax.swing.JMenuItem();
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setTitle("JLChat");
- jTextField1.setText("admin");
- jLabel1.setFont(new java.awt.Font("SansSerif", 0, 10)); // NOI18N
- jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
- jLabel1.setText("Ваше Имя");
- jTextField2.setText("localhost");
- jLabel2.setFont(new java.awt.Font("SansSerif", 0, 10)); // NOI18N
- jLabel2.setText("IP Сервера");
- jTextField3.setText("1777");
- jLabel3.setFont(new java.awt.Font("SansSerif", 0, 10)); // NOI18N
- jLabel3.setText("Порт Сервера");
- jTextArea1.setEditable(false);
- jTextArea1.setColumns(20);
- jTextArea1.setLineWrap(true);
- jTextArea1.setRows(5);
- jTextArea1.setWrapStyleWord(true);
- jTextArea1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
- jScrollPane1.setViewportView(jTextArea1);
- jButton3.setText("Отправить");
- jButton3.setToolTipText("");
- jButton3.setEnabled(false);
- jButton3.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton3ActionPerformed(evt);
- }
- });
- jTextArea2.setColumns(20);
- jTextArea2.setFont(new java.awt.Font("Serif", 0, 12)); // NOI18N
- jTextArea2.setLineWrap(true);
- jTextArea2.setRows(5);
- jTextArea2.setWrapStyleWord(true);
- jTextArea2.setEnabled(false);
- jScrollPane2.setViewportView(jTextArea2);
- jTextArea3.setEditable(false);
- jTextArea3.setColumns(20);
- jTextArea3.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
- jTextArea3.setLineWrap(true);
- jTextArea3.setRows(5);
- jTextArea3.setText("Инструкция:\n\n1) Создаём сервер (можно сразу нажать кнопку \"Cоединить\")\n\n2) Присоединяемся к серверу (только один клиент может подключиться к серверу):\n\nа) Ввести в поле \"IP Сервера\" адрес хоста (например, 192.168.0.111)\nб) Ввести в поле \"Порт Сервера\" порт хоста\nв) Нажать кнопку \"Cоединить\"\n\n3) Чатимся =)\n\n4) Разъединять коннект нужно с двух сторон и потом повторить шаги 1-3 для восстановления соединения.\n\nПриятной беседы!");
- jTextArea3.setWrapStyleWord(true);
- jScrollPane3.setViewportView(jTextArea3);
- buttonGroup1.add(jRadioButton1);
- jRadioButton1.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
- jRadioButton1.setSelected(true);
- jRadioButton1.setText("Сервер");
- buttonGroup1.add(jRadioButton2);
- jRadioButton2.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
- jRadioButton2.setText("Клиент");
- jLabel4.setFont(new java.awt.Font("SansSerif", 0, 10)); // NOI18N
- jLabel4.setText("Соединить как");
- jButton1.setText("Соединить");
- jButton1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton1ActionPerformed(evt);
- }
- });
- jButton2.setText("Разьединить");
- jButton2.setEnabled(false);
- jButton2.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton2ActionPerformed(evt);
- }
- });
- jMenu1.setText("Файл");
- jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
- jMenuItem1.setText("Выход");
- jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jMenuItem1ActionPerformed(evt);
- }
- });
- jMenu1.add(jMenuItem1);
- jMenuBar1.add(jMenu1);
- jMenu2.setText("Информация");
- jMenuItem3.setText("Об авторе");
- jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jMenuItem3ActionPerformed(evt);
- }
- });
- jMenu2.add(jMenuItem3);
- jMenuBar1.add(jMenu2);
- setJMenuBar(jMenuBar1);
- 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, false)
- .addGroup(layout.createSequentialGroup()
- .addGap(4, 4, 4)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
- .addComponent(jLabel2)
- .addComponent(jLabel3)
- .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jLabel4))
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
- .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
- .addGroup(layout.createSequentialGroup()
- .addGap(37, 37, 37)
- .addComponent(jRadioButton1)
- .addGap(18, 18, 18)
- .addComponent(jRadioButton2))))
- .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
- .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addComponent(jScrollPane1)))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(jScrollPane1)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
- .addGroup(layout.createSequentialGroup()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(jTextField1)
- .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(jTextField2)
- .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(jTextField3)
- .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jRadioButton2)
- .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(jRadioButton1))
- .addGap(6, 6, 6)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)))
- .addContainerGap())
- );
- pack();
- }// </editor-fold>
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- jButton1.setEnabled(false);
- jButton2.setEnabled(true);
- jRadioButton1.setEnabled(false);
- jRadioButton2.setEnabled(false);
- jTextField1.setEnabled(false);
- jTextField2.setEnabled(false);
- jTextField3.setEnabled(false);
- userName = jTextField1.getText();
- serverIP = jTextField2.getText();
- serverPort = Integer.parseInt(jTextField3.getText());
- begin = true;
- connect = false;
- }
- private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
- jButton1.setEnabled(true);
- jButton2.setEnabled(false);
- jButton3.setEnabled(false);
- jRadioButton1.setEnabled(true);
- jRadioButton2.setEnabled(true);
- jTextField1.setEnabled(true);
- jTextField2.setEnabled(true);
- jTextField3.setEnabled(true);
- jTextArea2.setEnabled(false);
- begin = false;
- connect = false;
- if (jRadioButton1.isSelected()) {
- try {
- if (br != null && bw != null) {
- br.close();
- bw.flush();
- bw.close();
- }
- if (socket != null) {
- socket.close();
- }
- serverSocket.close();
- br = null;
- bw = null;
- socket = null;
- serverSocket = null;
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- } else {
- try {
- if (br != null && bw != null) {
- br.close();
- bw.flush();
- bw.close();
- }
- if (socket != null) {
- socket.close();
- }
- br = null;
- bw = null;
- socket = null;
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
- s = jTextArea2.getText();
- sendMessageMethod(s);
- }
- private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
- JOptionPane.showConfirmDialog(
- null,
- "Евгений Осипов, 2012 год. \n"
- + "osipoveg1990@gmail.com, www.fastandclever.ru",
- "Об Авторе", JOptionPane.PLAIN_MESSAGE,
- JOptionPane.PLAIN_MESSAGE);
- }
- private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
- System.exit(0);
- }
- private synchronized void startServerSockets() {
- try {
- serverSocket = new ServerSocket(serverPort);
- socket = serverSocket.accept();
- begin = false;
- connect = true;
- br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
- bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
- jTextArea2.setEnabled(true);
- jButton3.setEnabled(true);
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- private synchronized void startClientSockets() {
- try {
- socket = new Socket(serverIP, serverPort);
- begin = false;
- connect = true;
- br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
- bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
- jTextArea2.setEnabled(true);
- jButton3.setEnabled(true);
- } catch (UnknownHostException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- private synchronized void sendMessageMethod(String s1) {
- sendMessage.append(userName).append(": ").append(s1).append("\n");
- }
- private synchronized void chatMessageMethod(String s2) {
- chatMessage.append(s2).append("\n");
- }
- private synchronized void sendMessageSafe() {
- try {
- bw.write(sendMessage.toString());
- bw.flush();
- this.jTextArea1.append(sendMessage.toString());
- sendMessage.setLength(0);
- jTextArea2.setText("");
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- private synchronized void chatMessageSafe() {
- try {
- s = br.readLine();
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- chatMessageMethod(s);
- jTextArea1.append(chatMessage.toString());
- chatMessage.setLength(0);
- }
- /**
- * @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(JLChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(JLChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(JLChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(JLChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- }
- //</editor-fold>
- /* Create and display the form */
- JLChat jlch = new JLChat();
- jlch.setVisible(true);
- while (true) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- if (jlch.begin) {
- if (jlch.jRadioButton1.isSelected()) {
- jlch.startServerSockets();
- } else if (jlch.jRadioButton2.isSelected()) {
- jlch.startClientSockets();
- }
- }
- if (jlch.connect) {
- try {
- if (jlch.sendMessage.length() != 0) {
- jlch.sendMessageSafe();
- }
- if (jlch.br.ready()) {
- jlch.chatMessageSafe();
- }
- } catch (IOException ex) {
- Logger.getLogger(JLChat.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- }
- // Объявления собственных полей
- private String serverIP;
- private int serverPort;
- private ServerSocket serverSocket;
- private Socket socket;
- private String userName;
- private String s;
- private StringBuffer sendMessage = new StringBuffer("");
- public StringBuffer chatMessage = new StringBuffer("");
- private BufferedWriter bw;
- private BufferedReader br;
- private boolean begin;
- private boolean connect;
- // Конец объявления собственных полей
- // Variables declaration - do not modify
- private javax.swing.ButtonGroup buttonGroup1;
- private javax.swing.JButton jButton1;
- private javax.swing.JButton jButton2;
- private javax.swing.JButton jButton3;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JLabel jLabel3;
- private javax.swing.JLabel jLabel4;
- private javax.swing.JMenu jMenu1;
- private javax.swing.JMenu jMenu2;
- private javax.swing.JMenuBar jMenuBar1;
- private javax.swing.JMenuItem jMenuItem1;
- private javax.swing.JMenuItem jMenuItem3;
- private javax.swing.JRadioButton jRadioButton1;
- private javax.swing.JRadioButton jRadioButton2;
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JScrollPane jScrollPane2;
- private javax.swing.JScrollPane jScrollPane3;
- private javax.swing.JTextArea jTextArea1;
- private javax.swing.JTextArea jTextArea2;
- private javax.swing.JTextArea jTextArea3;
- private javax.swing.JTextField jTextField1;
- private javax.swing.JTextField jTextField2;
- private javax.swing.JTextField jTextField3;
- // End of variables declaration
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement