java - 将变量传递给Java线程(run()方法)

标签 java sockets

我试图将变量“名称”从我的主要方法传递给run()方法。

我已经尝试过这种方式how can I pass a variable into a new Runnable declaration?

但是我无法使它正常工作。如何传递该变量? (我已经插入了完整运行程序所需的另一个类。)

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.InetAddress;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;



public class Server {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {

        try {
            final int port = 8181;
            ServerSocket server = new ServerSocket(port);
            System.out.println("Server is up and running, waiting for clients to connect.");

            while (true) {
                Socket sock = server.accept();
                System.out.println("A new user has connected");
                System.out.println("Type \"LIST\" to get a list of commands");
                System.out.println("Enter your Username"); final String name = input.nextLine();
                System.out.println("Now go to the client console to enter your messages");
                new Thread(new Client(sock)).start();
            }

        } catch (Exception e) {
            System.out.println("An error occured.");
            e.printStackTrace();
        }
    }

    static class Client implements Runnable {

        private Socket socket;
        int id;

        public Client(Socket sock)

        {
            id = 1;
            socket = sock;
        }

        @Override
        public void run() {

            long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime();
            RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();

            try {

                Scanner in = new Scanner(socket.getInputStream());
                PrintWriter out = new PrintWriter(socket.getOutputStream());

                while (true) {

                    String data = in.nextLine();
                    System.out.println("User : " + data);

                    if (data.startsWith("LEAVENOW")) {
                        System.out.println("Client has left the server");
                        break;
                    }

                    if (data.startsWith("GETIP")) {
                        // System.out.println("Client connected from " +
                        // InetAddress.getLocalHost());
                        System.out.println("Client connected from " + InetAddress.getLocalHost());

                    }
                    if (data.startsWith("SERVERTIME")) {
                        System.out.println(mxBean.getUptime());

                    }
                    /*
                     * if (data.startsWith("SETNAME")) {
                     * 
                     * Scanner input = new Scanner(System.in);
                     * 
                     * System.out.println("Enter your Username"); final String
                     * name = input.nextLine();
                     * System.out.println("Press 1 to confirm your user name");
                     * int namenum = input.nextInt(); if (namenum == 1){
                     * 
                     * System.out.println("name changed"); }
                     * 
                     * 
                     * }
                     */
                    if (data.startsWith("LIST")) {
                        System.out.println("Here is a list of commands that the user can use in the server");
                        System.out.println(
                                "LEAVENOW = exit the server \nGETIP = Gets the IP address of the server \nSERVERTIME = The amount of milliseconds the server has been running \n ");

                    }

                    // send the line back to the client
                    // or whatever custom message we want
                    // out.println(line);
                    // out.flush();

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

运行完整程序的附加类
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClientInstance {
    final static int port = 8181;
    final static String host = "localhost";

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws IOException {

        try {

            Socket sock = new Socket(host, port);

            System.out.println("You connected to " + host);
            System.out.println("Now enter your message ");

            new Thread(new ClientWriter(sock)).start();
            new Thread(new ClientReader(sock)).start();

        } catch (Exception CannotConnect) {
            System.err.println("Could not connect to the server please try again, if error proceeds restart IDE");
        }
    }


    static class ClientWriter implements Runnable {

        public Socket socket;

        public ClientWriter(Socket sock) {
            socket = sock;
        }

        public void run() {
            try {
                Scanner chat = new Scanner(System.in);
                PrintWriter out = new PrintWriter(socket.getOutputStream());

                while (true) {

                    String input = chat.nextLine();
                    out.println(input);
                    out.flush();

                }

            } catch (Exception e) {
                e.printStackTrace();

            }
        }


    }

    static class ClientReader implements Runnable {

        public Socket socket;

        public ClientReader(Socket sock) {
            socket = sock;
        }

        public void run() {
            try {
                /* Scanner scanner = new Scanner(socket.getInputStream());
                  //read data from client
                 while(true) {
                      String data = scanner.nextLine();
                      System.out.println("Received data! : " + data);
                  }
                  */

            } catch (Exception e) {
                e.printStackTrace();

            }
        }


    }
}

因此,根据@Berger的建议,我更改了代码并编辑了这一部分。我所做的就是将字符串名称添加为参数,就像使用套接字 socks 一样。但是,当我在run()方法中调用name变量时,字符串仅显示null。
new Thread(new Client(sock, name)).start();
            }

        } catch (Exception e) {
            System.out.println("An error occured.");
            e.printStackTrace();
        }
    }

    static class Client implements Runnable {

        private Socket socket;
        int id;
        String name;

        public Client(Socket sock, String name)

        {
            id = 1;
            socket = sock;
            name = name;
        }

最佳答案

您需要以适当的方式分配字段。您需要执行以下操作。

this.name = name;

您有两个名为name的不同变量。一个是local variable(方法参数),另一个是instance field

您所做的是通过name = name;将您本地变量name引用的字符串辅助到同一本地变量name,相反,您应该做的是将本地变量name引用的字符串分配给实例字段name(即this.name)。

关于java - 将变量传递给Java线程(run()方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103815/

相关文章:

java - 如何在 Java 中定位 JLabel 并调整其大小?

java - 在使用 Spring + Hibernate JPA 时不添加 persistence.xml 时使用 native SQL 实体

java - 使用 JDBC 连接到 MySQL

java - 如何创建第二个类并将Test设置为TextView?

Java:如何在 "regular"TCP Socket和SSLSocket之间进行抽象

c - 尝试连接到已处理请求的套接字的传入连接会发生什么情况?

linux - tsc 的 SO_TIMESTAMP 不是 timeval?

java - 开始 Java Web 服务。从哪儿开始

java - Android BSD 套接字连接

python - 使用IP地址在python中查找位置