在java中追加字符串的奇怪障碍

时间:2014-02-23 16:13:57

标签: java

我想将一些子字符串附加到名称为Request的字符串变量,但它不起作用,请求保持为空,带有“”值。真的很奇怪 请求是StringBuilder和我的类的成员。 客户端是Socket的一个实例。 注意:tmp不是空的......

任何人都可以帮助我吗? (代码已更改)

class Threading extends Thread
{
Socket server;
Socket client;
StringBuilder Request;

Threading(Socket sck,Socket srv)
{
    client = sck;
    server = srv;
    Request = new StringBuilder();
}

@Override
public void run() {
    try
    {
        DataOutputStream clientout = new DataOutputStream(client.getOutputStream());
        BufferedReader clientinput = new BufferedReader(new InputStreamReader(client.getInputStream()));
        System.out.println("---------REQUEST--------");
        String tmp ="THIS";

        while((tmp=clientinput.readLine())!=null)
        {
            Request = Request.append(tmp);
        }
        System.out.println(Request.toString());//Request is empty!!!
        DataOutputStream srvout = new DataOutputStream(server.getOutputStream());
        BufferedReader srvin = new BufferedReader(new InputStreamReader(server.getInputStream()));
        srvout.write(Request.toString().getBytes());
        while((tmp=srvin.readLine())!=null)
        {
            clientout.write(tmp.getBytes());
        }
    }
    catch(IOException e){e.printStackTrace();}
}

我把所有的课程代码都放了。 谢谢你的回复。

1 个答案:

答案 0 :(得分:0)

我正在运行你的代码的一个小修改版本(因为没有处理套接字),我得到了预期的行为:

也许另一个线程会覆盖Request?尝试使用局部变量 您是否100%确定clientinput有数据?包括换行符?

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class Tmp {
public static void main(String[] args) {
    new Tmp().run();
}

StringBuilder request = new StringBuilder(); 
public void run() {

    String test= "testData\r\n";
    ByteArrayInputStream client = new ByteArrayInputStream(test.getBytes()); 
    try
    {
        BufferedReader clientinput = new BufferedReader(new InputStreamReader(client));
        System.out.println("---------REQUEST--------");
        String tmp;

        while((tmp=clientinput.readLine())!=null)
        {
            request = request.append(tmp);
        }
        System.out.println(request.toString());//request is NOT empty!!!
    }
    catch(IOException e){e.printStackTrace();}
}         
}