简体   繁体   中英

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.

Since accept() method of server class waits for the client socket object, so before this line System.out.println(Myclient1.nameOfClient + " connected"); gets executed, client would already have entered his name in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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