这是一个小的telnet程序,最后想得到的结果是执行指定命令后返回执行命令的结果,也就是说要好如何取得reString的值,目前的这段程序返回的reString值为null,但是在run()那段程序里已经有取得返回值了,请各位帮忙,谢谢。程序如下:
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;public class MyTelnet
{
//-----定义变量名-----
protected Socket socket;
public OutputStream output;
public BufferedInputStream input;
//-----定义返回变量名-----
static String reString = null;


public String getOpenConnection(String host,int port,String command)
{

//-----建立Socket连接,并定义输入、输出流-----
try
{
socket = new Socket(host,port);
output = socket.getOutputStream();
input = new BufferedInputStream(socket.getInputStream());
}catch(IOException ie)
{
     String title = "建立输入输出流时产生错误";
     String message = "建立输入输出流时产生错误\n" + ie.getMessage();
     new ErrorMessage(message,title);
}

//-----定义线程并连接-----
try
{//System.out.println("在线程执行前reString:" + reString);
ByteArrayInputStream bais = new ByteArrayInputStream(command.getBytes());
outputStreamConnect in_to_socket = new outputStreamConnect(bais,output);
inputStreamConnect out_to_socket = new inputStreamConnect(input,System.out);

Thread input_Thread = new Thread(in_to_socket);
Thread output_Thread = new Thread(out_to_socket);

input_Thread.start();
output_Thread.start();
//System.out.println("在线程执行后reString:" + reString);
}catch(Exception e)
{
     String title = "telnet连接时产生错误";
     String message = "telnet连接时产生错误\n" + e.getMessage();
}

     return reString;
}

//-----使用线程连接输入流-----
class outputStreamConnect implements Runnable
{
InputStream in = null;
OutputStream out = null;
public outputStreamConnect(InputStream input,OutputStream ou)
{
in = input;
out = ou;
}

public void run()
{
byte[] buff = new byte[1024];
while(true)
{
try
{
int n = in.read(buff);
if(n > 0)
{
out.write(buff,0,n);
out.flush();
}
}catch(Exception e)
{
     String title = "输入命令流时产生错误";
String message = "输入命令流时产生错误\n" + e.getMessage();
new ErrorMessage(message,title);
}
}
}
}

//------使用线程连接输出流-----
class inputStreamConnect implements Runnable
{
InputStream in = null;
OutputStream out = null;
public inputStreamConnect(InputStream input,OutputStream ou)
{
in = input;
out = ou;
}

public void run()
{
byte[] buff = new byte[1024];
while(true)
{
try
{
int n = in.read(buff);
if(n > 0)
{
reString += new String(buff,0,n);//System.out.println("在线程里的reString:" + reString);
}
}catch(Exception e)
{
String title = "输出返回数据时产生错误";
String message = "输出返回数据时产生错误\n" + e.getMessage();
new ErrorMessage(message,title);
}
}
}
}
}

解决方案 »

  1.   

    我觉得这是一个程序执行时的先后问题,你可以在output_Thread.start();后面加上一句
    Thread.sleep(10000);这个值可以根据程序执行的时间长短来定。
    这样线程执行完后才会有返回值。
      

  2.   

    时序问题getOpenConnection中启动2个线程,很快就退出了 (两个线程什么时间执行不确定,所以就出现你描述的问题,getOpenConnection先退出, run后执行)
      

  3.   

    不好意思,给错分了。我别开帖子给分。请WindDesertWater过来拿分。