【问题标题】:Passing variable value from one class to another Java将变量值从一个类传递到另一个 Java
【发布时间】:2016-12-05 23:53:08
【问题描述】:

如何在不创建新对象实例的情况下将变量值从一个类传递到另一个类? 基本上,我有这些客户端和服务器类,我想将客户端用户名值传输到服务器类,以便可以在“sendToAll”服务器方法中识别每个用户。

客户端类:

/*
 * 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();
            }
        }
    }
}

【问题讨论】:

  • 这种取决于你程序的结构。
  • 在服务器/客户端关系中通常通过网络通过套接字
  • 已发布服务器和客户端代码。感谢任何帮助

标签: java class dialog


【解决方案1】:

由于您正在处理通过套接字进行通信的两个不同进程(客户端和服务器),因此无法阻止创建新对象。

我猜标题和问题描述有点误导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多