Чат с GUI - Java

Узнай цену своей работы

Формулировка задачи:

Доброго времени суток. У меня такая проблема. У меня есть готовый код для сетевого чата на Java, сделанный по видео уроку. Проблема в том, что в данном уроке код был сделан так, чтобы можно было его презентовать на одном компьютере (2 пользователя на одном компьютере). Мне же для курсовой работы требуется продемонстрировать работу данной программы на 2 компьютерах. Заранее огромное спасибо. Вот сам код. Main.java
Листинг программы
  1. package LANChatv2;
  2. public class Main {
  3. /**
  4. * @param args the command line arguments
  5. */
  6. public static void main(String[] args) {
  7. // TODO code application logic here
  8. }
  9. }
Chat_Client.java
Листинг программы
  1. package LANChatv2;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.net.Socket;
  5. public class chat_client extends javax.swing.JFrame {
  6. static Socket s;
  7. static DataInputStream din;
  8. static DataOutputStream dout;
  9. public chat_client() {
  10. initComponents();
  11. }
  12. @SuppressWarnings("unchecked")
  13. // <editor-fold defaultstate="collapsed" desc="Generated Code">
  14. private void initComponents() {
  15. jScrollPane1 = new javax.swing.JScrollPane();
  16. msg_area = new javax.swing.JTextArea();
  17. msg_text = new javax.swing.JTextField();
  18. msg_send = new javax.swing.JButton();
  19. setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  20. setName("Client"); // NOI18N
  21. msg_area.setColumns(20);
  22. msg_area.setRows(5);
  23. jScrollPane1.setViewportView(msg_area);
  24. msg_send.setLabel("Send");
  25. msg_send.addActionListener(new java.awt.event.ActionListener() {
  26. public void actionPerformed(java.awt.event.ActionEvent evt) {
  27. msg_sendActionPerformed(evt);
  28. }
  29. });
  30. javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  31. getContentPane().setLayout(layout);
  32. layout.setHorizontalGroup(
  33. layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  34. .addGroup(layout.createSequentialGroup()
  35. .addGap(19, 19, 19)
  36. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  37. .addComponent(jScrollPane1)
  38. .addGroup(layout.createSequentialGroup()
  39. .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
  40. .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  41. .addComponent(msg_send, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)))
  42. .addContainerGap(23, Short.MAX_VALUE))
  43. );
  44. layout.setVerticalGroup(
  45. layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  46. .addGroup(layout.createSequentialGroup()
  47. .addGap(19, 19, 19)
  48. .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
  49. .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  50. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  51. .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
  52. .addComponent(msg_send, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
  53. .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  54. );
  55. pack();
  56. }// </editor-fold>
  57. private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
  58. try{
  59. String msgout = "";
  60. msgout = msg_text.getText().trim();
  61. dout.writeUTF(msgout);
  62. }
  63. catch(Exception e){
  64. }
  65. }
  66. /**
  67. * @param args the command line arguments
  68. */
  69. public static void main(String args[]) {
  70. /* Set the Nimbus look and feel */
  71. //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  72. /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  73. * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
  74. */
  75. try {
  76. for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  77. if ("Nimbus".equals(info.getName())) {
  78. javax.swing.UIManager.setLookAndFeel(info.getClassName());
  79. break;
  80. }
  81. }
  82. } catch (ClassNotFoundException ex) {
  83. java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  84. } catch (InstantiationException ex) {
  85. java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  86. } catch (IllegalAccessException ex) {
  87. java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  88. } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  89. java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  90. }
  91. //</editor-fold>
  92. /* Create and display the form */
  93. java.awt.EventQueue.invokeLater(new Runnable() {
  94. public void run() {
  95. new chat_client().setVisible(true);
  96. }
  97. });
  98. try{
  99. s = new Socket("127.0.0.1",1201);
  100. din = new DataInputStream(s.getInputStream());
  101. dout = new DataOutputStream(s.getOutputStream());
  102. String msgin="";
  103. while(!msgin.equals("exit")){
  104. msgin = din.readUTF();
  105. msg_area.setText(msg_area.getText().trim()+"\n Server:\t"+msgin);
  106. }
  107. }catch(Exception e){
  108. }
  109. }
  110. // Variables declaration - do not modify
  111. private javax.swing.JScrollPane jScrollPane1;
  112. private static javax.swing.JTextArea msg_area;
  113. private javax.swing.JButton msg_send;
  114. private javax.swing.JTextField msg_text;
  115. // End of variables declaration
  116. }
Chat_server.java
Листинг программы
  1. package LANChatv2;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6.  
  7. public class chat_server extends javax.swing.JFrame {
  8.  
  9. static ServerSocket ss;
  10. static Socket s;
  11. static DataInputStream din;
  12. static DataOutputStream dout;
  13. public chat_server() {
  14. initComponents();
  15. }
  16. @SuppressWarnings("unchecked")
  17. // <editor-fold defaultstate="collapsed" desc="Generated Code">
  18. private void initComponents() {
  19. jScrollPane1 = new javax.swing.JScrollPane();
  20. msg_area = new javax.swing.JTextArea();
  21. msg_text = new javax.swing.JTextField();
  22. msg_send = new javax.swing.JButton();
  23. setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  24. setName("Server"); // NOI18N
  25. msg_area.setColumns(20);
  26. msg_area.setRows(5);
  27. jScrollPane1.setViewportView(msg_area);
  28. msg_text.addActionListener(new java.awt.event.ActionListener() {
  29. public void actionPerformed(java.awt.event.ActionEvent evt) {
  30. msg_textActionPerformed(evt);
  31. }
  32. });
  33. msg_send.setText("Send");
  34. msg_send.addActionListener(new java.awt.event.ActionListener() {
  35. public void actionPerformed(java.awt.event.ActionEvent evt) {
  36. msg_sendActionPerformed(evt);
  37. }
  38. });
  39. javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  40. getContentPane().setLayout(layout);
  41. layout.setHorizontalGroup(
  42. layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  43. .addGroup(layout.createSequentialGroup()
  44. .addGap(24, 24, 24)
  45. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  46. .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
  47. .addGroup(layout.createSequentialGroup()
  48. .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)
  49. .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  50. .addComponent(msg_send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
  51. .addContainerGap(23, Short.MAX_VALUE))
  52. );
  53. layout.setVerticalGroup(
  54. layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  55. .addGroup(layout.createSequentialGroup()
  56. .addGap(12, 12, 12)
  57. .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
  58. .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  59. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  60. .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
  61. .addComponent(msg_send, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
  62. .addContainerGap())
  63. );
  64. pack();
  65. }// </editor-fold>
  66. private void msg_textActionPerformed(java.awt.event.ActionEvent evt) {
  67. }
  68. private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
  69. try{
  70. String msgout = "";
  71. msgout = msg_text.getText().trim();
  72. dout.writeUTF(msgout); //sending the sever message to the client.
  73. }catch(Exception e){
  74. //handle the exception here
  75. }
  76. }
  77. /**
  78. * @param args the command line arguments
  79. */
  80. public static void main(String args[]) {
  81. /* Set the Nimbus look and feel */
  82. //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  83. /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  84. * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
  85. */
  86. try {
  87. for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  88. if ("Nimbus".equals(info.getName())) {
  89. javax.swing.UIManager.setLookAndFeel(info.getClassName());
  90. break;
  91. }
  92. }
  93. } catch (ClassNotFoundException ex) {
  94. java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  95. } catch (InstantiationException ex) {
  96. java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  97. } catch (IllegalAccessException ex) {
  98. java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  99. } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  100. java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  101. }
  102. //</editor-fold>
  103. /* Create and display the form */
  104. java.awt.EventQueue.invokeLater(new Runnable() {
  105. public void run() {
  106. new chat_server().setVisible(true);
  107. }
  108. });
  109. String msgin = "";
  110. try{
  111. ss = new ServerSocket(1201); //server starts at 1201 port number
  112. s = ss.accept();
  113. din = new DataInputStream(s.getInputStream());
  114. dout = new DataOutputStream(s.getOutputStream());
  115. while(!msgin.equals("exit")){
  116. msgin = din.readUTF();
  117. msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
  118. }
  119.  
  120. }catch(Exception e){
  121. }
  122.  
  123. }
  124. // Variables declaration - do not modify
  125. private javax.swing.JScrollPane jScrollPane1;
  126. private static javax.swing.JTextArea msg_area;
  127. private javax.swing.JButton msg_send;
  128. private javax.swing.JTextField msg_text;
  129. // End of variables declaration
  130. }

Решение задачи: «Чат с GUI»

textual
Листинг программы
  1. s = new Socket("ip сервера(компьютера на котором запущен сервер)",1201);

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 4.077 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут