2016-12-05 250 views
-2

如何在不創建新對象實例的情況下將變量值從一個類傳遞到另一個類? 基本上,我有這些客戶端和服務器類,我想將客戶端用戶名值傳輸到服務器類,以便每個用戶都可以在「sendToAll」服務器方法中識別。將變量值從一個類傳遞給另一個Java

Client類:

/* 
 
* To change this license header, choose License Headers in Project Properties. 
 
* To change this template file, choose Tools | Templates 
 
* and open the template in the editor. 
 
*/ 
 
package chat; 
 

 
import java.io.*; 
 
import java.net.*; 
 
import javax.swing.JOptionPane; 
 

 
/** 
 
* 
 
* @author Allura 
 
*/ 
 
public class ChatClient extends javax.swing.JFrame { 
 
    BufferedReader reader; 
 
    PrintWriter writer; 
 
    String username; 
 
    /** 
 
    * Creates new form ChatClient 
 
    */ 
 
    public ChatClient() { 
 
     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() { 
 

 
     jScrollPane1 = new javax.swing.JScrollPane(); 
 
     messageBox = new javax.swing.JTextArea(); 
 
     inputBox = new javax.swing.JTextField(); 
 
     sendButton = new javax.swing.JButton(); 
 

 
     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
 

 
     messageBox.setEditable(false); 
 
     messageBox.setColumns(20); 
 
     messageBox.setRows(5); 
 
     jScrollPane1.setViewportView(messageBox); 
 

 
     sendButton.setText("Send"); 
 
     sendButton.addActionListener(new java.awt.event.ActionListener() { 
 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
 
       sendButtonActionPerformed(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() 
 
       .addContainerGap() 
 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
 
        .addGroup(layout.createSequentialGroup() 
 
         .addComponent(inputBox, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE) 
 
         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
 
         .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)) 
 
        .addComponent(jScrollPane1)) 
 
       .addContainerGap()) 
 
     ); 
 
     layout.setVerticalGroup(
 
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
 
      .addGroup(layout.createSequentialGroup() 
 
       .addContainerGap() 
 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE) 
 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) 
 
        .addComponent(inputBox) 
 
        .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)) 
 
       .addContainerGap(23, Short.MAX_VALUE)) 
 
     ); 
 

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

 
    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {           
 
     if(!inputBox.getText().equals("")) 
 
     { 
 
      try 
 
      { 
 
       writer.println(inputBox.getText()); 
 
       writer.flush(); 
 
      } 
 
      catch(Exception ex) 
 
      { 
 
       ex.printStackTrace(); 
 
      } 
 
     } 
 
    }           
 

 
    /** 
 
    * @param args the command line arguments 
 
    */ 
 
    public static void main(String args[]) { 
 
     ChatClient client = new ChatClient(); 
 
     client.go(); 
 
    } 
 
    public void go() 
 
    { 
 
     username = JOptionPane.showInputDialog(this, "Enter a username: "); 
 
     setUpNetwork(); 
 
     setVisible(true); 
 
     Thread myRunner = new Thread(new MessageReader()); 
 
     myRunner.start(); 
 
    } 
 
    public void setUpNetwork() 
 
    { 
 
     try 
 
     { 
 
      Socket sock = new Socket("0.0.0.0", 5000); 
 
      InputStreamReader input = new InputStreamReader(sock.getInputStream()); 
 
      reader = new BufferedReader(input); 
 
      writer = new PrintWriter(sock.getOutputStream()); 
 
      System.out.println("Connection established."); 
 
     } 
 
     catch(IOException ex) 
 
     { 
 
      ex.printStackTrace(); 
 
     } 
 
    } 
 
    public class MessageReader implements Runnable 
 
    { 
 
     String message; 
 
     public void run() 
 
     { 
 
      try 
 
      { 
 
       while ((message = reader.readLine()) != null) 
 
       { 
 
        messageBox.append(message + "\n"); 
 
       } 
 
      } 
 
      catch(Exception ex) 
 
      { 
 
       ex.printStackTrace(); 
 
      } 
 
     } 
 
    } 
 
    // Variables declaration - do not modify      
 
    private javax.swing.JTextField inputBox; 
 
    private javax.swing.JScrollPane jScrollPane1; 
 
    private javax.swing.JTextArea messageBox; 
 
    private javax.swing.JButton sendButton; 
 
    // End of variables declaration     
 
}

服務器類:

/* 
 
* To change this license header, choose License Headers in Project Properties. 
 
* To change this template file, choose Tools | Templates 
 
* and open the template in the editor. 
 
*/ 
 
package chat; 
 
import java.net.*; 
 
import java.io.*; 
 
import java.util.*; 
 
import javax.swing.*; 
 
/** 
 
* 
 
* @author Allura 
 
*/ 
 
public class ChatServer extends JFrame { 
 
    ArrayList StreamOutput; 
 
    Socket mainSocket; 
 
    
 
    public class ClientHandler implements Runnable 
 
    { 
 
     Socket sock; 
 
     BufferedReader reader; 
 
     public ClientHandler(Socket clientSock) 
 
     { 
 
      try 
 
      { 
 
       sock = clientSock; 
 
       InputStreamReader input = new InputStreamReader(sock.getInputStream()); 
 
       reader = new BufferedReader(input); 
 
      } 
 
      catch(Exception ex) 
 
      { 
 
       ex.printStackTrace(); 
 
      } 
 
     } 
 
     public void run() 
 
     { 
 
      String message; 
 
      try 
 
      { 
 
       while((message = reader.readLine()) != null) 
 
       { 
 
        sendToAll(message); 
 
       } 
 
      } 
 
      catch(Exception ex) 
 
      { 
 
       ex.printStackTrace(); 
 
      } 
 
     } 
 
    } 
 
    public static void main(String[] args) 
 
    { 
 
     new ChatServer().go(); 
 
    } 
 
    public void go() 
 
    { 
 
     StreamOutput = new ArrayList(); 
 
     try 
 
     { 
 
      ServerSocket serverSock = new ServerSocket(5000); 
 
      while(true) 
 
      { 
 
       mainSocket = serverSock.accept(); 
 
       PrintWriter writer = new PrintWriter(mainSocket.getOutputStream()); 
 
       StreamOutput.add(writer); 
 
       System.out.println("Request from client accepted. Connection established."); 
 
       Thread myRunner = new Thread(new ClientHandler(mainSocket)); 
 
       myRunner.start(); 
 
      } 
 
     } 
 
     catch(Exception ex) 
 
     { 
 
      ex.printStackTrace(); 
 
     } 
 
    } 
 
    public void sendToAll(String message) 
 
    { 
 
     Iterator it = StreamOutput.iterator(); 
 
     while(it.hasNext()) 
 
     { 
 
      try 
 
      { 
 
       PrintWriter writer = (PrintWriter) it.next(); 
 
       writer.println(message); 
 
       writer.flush(); 
 
      } 
 
      catch(Exception ex) 
 
      { 
 
       ex.printStackTrace(); 
 
      } 
 
     } 
 
    } 
 
}

+0

這種取決於你的程序的結構。 –

+0

在服務器/客戶端關係中通常通過套接字網絡 – zapl

+0

發佈服務器和客戶端代碼。感謝任何幫助 –

回答

0

既然你是在處理兩個不同的processe (通過套接字進行通信的客戶端和服務器)無法阻止創建新對象。

我猜標題和問題描述有點誤導。

相關問題