没有用android接收网络数据?

时间:2014-02-07 02:21:55

标签: java android network-programming

这是我的Android版ConnectionThread 我已经尝试了几个小时,但我无法将数据从我的计算机发送到我正在制作的应用程序..任何帮助都会很棒......如果您需要了解更多信息,请发表评论..没有例外被抛出我知道正在建立联系..

public class ConnectionThread implements Runnable {

private final int PORT = 4567;
private static PrintWriter out = null;
private BufferedReader in = null;
Socket kkSocket = null;
String ip = "";
//LoginActivity a;

public ConnectionThread(/*LoginActivity a,*/String ip) {
     this.ip = ip;
}

public void run() {
    try {
        // this.a = a;
            kkSocket = new Socket(ip, PORT);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(
                    new InputStreamReader(kkSocket.getInputStream()));
        //    a.makeToast("CONNECTION SUCCESS!!");
        } catch (IOException ex) {
            //Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
        //  a.makeToast("UNABLE TO CONNECT TO:"+ ip);
            Log.e("PPChat", "UNABLE TO CONNECT");
        }
    String fromServer = null;
    try {
        while ((fromServer = in.readLine()) == null) {
            Log.e("PP", "it happened...");
            FullscreenActivity.appendText(fromServer);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("READ ERROR", "was unable to read from the socket");
        //a.makeToast("was unable to read from the socket");
    }
    Log.e("PPChat", "connection is done");
}

public static boolean sendNetworkMessage(String str) {
    try{
    out.println(str);
    out.flush();
    } catch(Exception e) {
        return false;
    }
    return true;
}

}

这是发送网络数据的线程..我知道正在建立连接..我想我只是做了一个我没有看到的简单错误..

public class ConnectionThread extends Thread{
private Socket socket = null;
private String inputLine;
public static PrintWriter out = null;
public ConnectionThread(Socket accept) {
    super("ConnectionThread");
    this.socket = accept;
}

@Override
public void run() {

    try {
    System.out.println("connection made");
        out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        socket.getInputStream()));
        while ((inputLine = in.readLine()) != null) {
            System.out.println("server recieved: " +inputLine);
        }
    } catch(Exception e) {

    }
    System.out.println("thread is finished");
}
}

这里是我实际在线程中发送数据的地方,它从用户那里获取输入以发送数据

public class InputThread extends Thread{

private Scanner sc = null;

public InputThread() {
    sc = new Scanner(System.in);
}

@Override
public void run() {
    while(true) {
        String temp = sc.nextLine();
        ConnectionThread.out.println(temp);
        System.out.println("i wrote that: "+temp);
    }
}

}

抱歉,如果这真的很容易..我正在

1 个答案:

答案 0 :(得分:1)

为什么不使用Android AsyncTask来执行此类操作。我真的不知道你的确切要求,但通常做这种背景工作,建议使用AsyncTask。请参考此

http://developer.android.com/reference/android/os/AsyncTask.html