简体   繁体   English

为什么以下代码打印为空?

[英]Why does the following code print null?

I am trying to make client-server connection. 我正在尝试建立客户端-服务器连接。 First I have executed server code in one console and then client code in another console. 首先,我在一个控制台中执行了服务器代码,然后在另一个控制台中执行了客户端代码。 I want that after the client code runs, the client enters his name and then I will create the object of client socket class and print the name of client in the server console. 我希望在客户端代码运行之后,客户端输入其名称,然后创建客户端套接字类的对象,并在服务器控制台中打印客户端的名称。 But on the server console it prints null when I try to print the name of client. 但是在服务器控制台上,当我尝试打印客户端名称时,它会显示null

Since accept() method of server class waits for the client socket object, so before this line System.out.println(Myclient1.nameOfClient + " connected"); 由于服务器类的accept()方法等待客户端套接字对象,因此在此行之前System.out.println(Myclient1.nameOfClient + " connected"); gets executed, client would already have entered his name in String nameOfClient . 被执行后,客户端将已经在String nameOfClient输入了他的名字。

I am unable to understand the reason behind this. 我无法理解其背后的原因。

Server code 服务器代码

public Myserver1() {
    try {
        ss = new ServerSocket(10);
        while (true) {
            s = ss.accept(); // waits for the client socket
            System.out.println(Myclient1.nameOfClient + " connected"); // Here I want to print the name of client(Myclient1.java).

            al.add(s);
            Runnable r = new MyThread(s, al);
            Thread t = new Thread(r);
            t.start();
        }
    } catch(Exception e) {}
}

Client code 客户代码

public Myclient1() {
    System.out.println("enter ur name");
    nameOfClient = new Scanner(System.in).nextLine(); // Here I am storing the name of client so that I can access nameOfClient from Myserver1.java

    try {

        s = new Socket("localhost", 10);

        din = new DataInputStream(s.getInputStream());
        dout = new DataOutputStream(s.getOutputStream());
        clientchat();
    } catch(Exception e) {} 
}

Server and clients should run independently of each other, or else it defeats the purpose of networking. 服务器和客户端应彼此独立运行,否则将无法实现联网目的。 Right now, you are accessing a static variable the has never been initalized because the client isnt running in the same process as the server.Send the name over a socket, and use that as your print and your problem will be fixed. 现在,您正在访问一个从未初始化过的静态变量,因为客户端不在与服务器相同的进程中运行。通过套接字发送名称,然后将该名称用作打印内容即可解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM