Чат с GUI - Java
Формулировка задачи:
Доброго времени суток. У меня такая проблема. У меня есть готовый код для сетевого чата на Java, сделанный по видео уроку. Проблема в том, что в данном уроке код был сделан так, чтобы можно было его презентовать на одном компьютере (2 пользователя на одном компьютере). Мне же для курсовой работы требуется продемонстрировать работу данной программы на 2 компьютерах. Заранее огромное спасибо.
Вот сам код.
Main.java
Chat_Client.java
Chat_server.java
Листинг программы
- package LANChatv2;
- public class Main {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- // TODO code application logic here
- }
- }
Листинг программы
- package LANChatv2;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.net.Socket;
- public class chat_client extends javax.swing.JFrame {
- static Socket s;
- static DataInputStream din;
- static DataOutputStream dout;
- public chat_client() {
- initComponents();
- }
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">
- private void initComponents() {
- jScrollPane1 = new javax.swing.JScrollPane();
- msg_area = new javax.swing.JTextArea();
- msg_text = new javax.swing.JTextField();
- msg_send = new javax.swing.JButton();
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setName("Client"); // NOI18N
- msg_area.setColumns(20);
- msg_area.setRows(5);
- jScrollPane1.setViewportView(msg_area);
- msg_send.setLabel("Send");
- msg_send.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- msg_sendActionPerformed(evt);
- }
- });
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
- getContentPane().setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(19, 19, 19)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(jScrollPane1)
- .addGroup(layout.createSequentialGroup()
- .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(msg_send, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)))
- .addContainerGap(23, Short.MAX_VALUE))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(19, 19, 19)
- .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(msg_send, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
- );
- pack();
- }// </editor-fold>
- private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
- try{
- String msgout = "";
- msgout = msg_text.getText().trim();
- dout.writeUTF(msgout);
- }
- catch(Exception e){
- }
- }
- /**
- * @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 [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
- */
- 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(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(chat_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(chat_client.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 chat_client().setVisible(true);
- }
- });
- try{
- s = new Socket("127.0.0.1",1201);
- din = new DataInputStream(s.getInputStream());
- dout = new DataOutputStream(s.getOutputStream());
- String msgin="";
- while(!msgin.equals("exit")){
- msgin = din.readUTF();
- msg_area.setText(msg_area.getText().trim()+"\n Server:\t"+msgin);
- }
- }catch(Exception e){
- }
- }
- // Variables declaration - do not modify
- private javax.swing.JScrollPane jScrollPane1;
- private static javax.swing.JTextArea msg_area;
- private javax.swing.JButton msg_send;
- private javax.swing.JTextField msg_text;
- // End of variables declaration
- }
Листинг программы
- package LANChatv2;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class chat_server extends javax.swing.JFrame {
- static ServerSocket ss;
- static Socket s;
- static DataInputStream din;
- static DataOutputStream dout;
- public chat_server() {
- initComponents();
- }
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">
- private void initComponents() {
- jScrollPane1 = new javax.swing.JScrollPane();
- msg_area = new javax.swing.JTextArea();
- msg_text = new javax.swing.JTextField();
- msg_send = new javax.swing.JButton();
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setName("Server"); // NOI18N
- msg_area.setColumns(20);
- msg_area.setRows(5);
- jScrollPane1.setViewportView(msg_area);
- msg_text.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- msg_textActionPerformed(evt);
- }
- });
- msg_send.setText("Send");
- msg_send.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- msg_sendActionPerformed(evt);
- }
- });
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
- getContentPane().setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(24, 24, 24)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
- .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGroup(layout.createSequentialGroup()
- .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(msg_send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
- .addContainerGap(23, Short.MAX_VALUE))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(12, 12, 12)
- .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
- .addComponent(msg_text, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addComponent(msg_send, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addContainerGap())
- );
- pack();
- }// </editor-fold>
- private void msg_textActionPerformed(java.awt.event.ActionEvent evt) {
- }
- private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
- try{
- String msgout = "";
- msgout = msg_text.getText().trim();
- dout.writeUTF(msgout); //sending the sever message to the client.
- }catch(Exception e){
- //handle the exception here
- }
- }
- /**
- * @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 [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
- */
- 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(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(chat_server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(chat_server.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 chat_server().setVisible(true);
- }
- });
- String msgin = "";
- try{
- ss = new ServerSocket(1201); //server starts at 1201 port number
- s = ss.accept();
- din = new DataInputStream(s.getInputStream());
- dout = new DataOutputStream(s.getOutputStream());
- while(!msgin.equals("exit")){
- msgin = din.readUTF();
- msg_area.setText(msg_area.getText().trim()+"\n"+msgin);
- }
- }catch(Exception e){
- }
- }
- // Variables declaration - do not modify
- private javax.swing.JScrollPane jScrollPane1;
- private static javax.swing.JTextArea msg_area;
- private javax.swing.JButton msg_send;
- private javax.swing.JTextField msg_text;
- // End of variables declaration
- }
Решение задачи: «Чат с GUI»
textual
Листинг программы
- s = new Socket("ip сервера(компьютера на котором запущен сервер)",1201);
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д