我要在另外一个类中调用此变量
package certification;import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
Server manager = new Server();
manager.doListen();
}
public void doListen() {
ServerSocket server;
try {
server = new ServerSocket(9991);
while (true) {
Socket client = server.accept();
new Thread(new SSocket(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//服务器进程
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
this.client = client;
}
public void run() {
DataInputStream input;
DataOutputStream output;
try {
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
String listMsg = input.readUTF();
output.writeUTF("Recive: " + listMsg + " \r\n Thx...");
System.out.println("Recive: " + listMsg);
listMsg = input.readUTF();
output.writeUTF("Recive Second: " + listMsg + " \r\n Thx...");
System.out.println("Recive Second: " + listMsg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我想在另外一个类中调用此类中的listMsg变量。这个怎么调用啊?请高手赐教。
搜索更多相关的解决方案:
变量
----------------解决方案--------------------------------------------------------
把String listMsg定义为全局变量
----------------解决方案--------------------------------------------------------
回复 2楼 xwlking
不行的 我试过 。 ----------------解决方案--------------------------------------------------------
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
this.client = client;
}
String listMsg;
public String getListMsg(){
return listMsg;
}
public void setListMsg(String listMsg){
this.listMsg = listMsg;
}
public void run() {
DataInputStream input;
DataOutputStream output;
try {
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
setListMsg(input.redUTF());
output.writeUTF("Recive: " + listMsg + " \r\n Thx...");
System.out.println("Recive: " + listMsg);
listMsg = input.readUTF();
output.writeUTF("Recive Second: " + listMsg + " \r\n Thx...");
System.out.println("Recive Second: " + listMsg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
你试试这样呢 在另一个类中 调用此类的getListMsg()方法 试试;
----------------解决方案--------------------------------------------------------
你可以在要调用listMsg变量的类中写一个带String参数的构造方法,
在class SSocket类中把listMsg传过去,这也是一种方法,但不知道会不会有别的问题.
----------------解决方案--------------------------------------------------------
回复 4楼 dadongzicool
我调用getListMsg()的时候编译提示要我改成static。给了之后就可以调用了,但是传递的值是null。不是socket接收到的值啊这怎么弄啊?
----------------解决方案--------------------------------------------------------
回复 5楼 xwlking
我试试吧 现在主要的问题是每次传递的值是null ----------------解决方案--------------------------------------------------------