0
我正在尝试使客户端服务器连接。首先,我在一个控制台中执行服务器代码,然后在另一个控制台中执行客户端代码我希望在客户端代码运行后,客户端输入他的名字,然后创建客户端套接字类的对象并在服务器控制台中输出客户端的名称。但在服务器控制台上,当我尝试打印客户端的名称时,它会打印null
。为什么下面的代码打印为空?
由于服务器类的accept()
方法等待客户端Socket对象,所以这条线System.out.println(Myclient1.nameOfClient + " connected");
被执行之前,客户端将已经在String
nameOfClient
进入了他的名字。
我无法理解背后的原因。
Server代码
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) {}
}
客户端代码
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) {}
}
谢谢,我明白了。 – a874