2014-02-07 135 views
0

這是我的Android的ConnectionThread 我一直在嘗試幾個小時,但我無法從我的電腦發送數據到我的應用程序,我正在..任何幫助將是驚人的..只是評論,如果你需要知道再說了..沒有異常被拋出,我知道一個連接正在取得..未使用android接收網絡數據?

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

你爲什麼不使用Android的AsyncTask做這種工作。我真的不知道你的具體要求,但通常做這種背景的作品,建議使用AsyncTask。請參考

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

+0

好的,我在看,但它說AsyncTask中的東西應該只有幾秒鐘..然而,我的代碼可能永遠等待來自服務器端的輸入.. –