Android使用socket从pc获取数据

时间:2014-08-01 15:54:14

标签: android sockets

Android将数据发送到PC - 客户端(成功工作):

Button send = (Button) findViewById(R.id.sendSocket);
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                Socket socket = new Socket("IP",8000);
                DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
                DOS.writeUTF("Hello");
                socket.close();
            }catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

现在如何继续收听来自pc(服务器端)的数据???

这就是我的尝试(不工作):

try {
     Boolean end = false;
     ServerSocket ss = new ServerSocket(8000);
     while(!end){
             //Server is waiting for client here, if needed
             Socket s = ss.accept();
             BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
             PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
             String st = input.readLine();
             recive.setText(st);
             s.close();
             //if ( STOPPING conditions){ end = true; }
         }
         ss.close();
     } catch (UnknownHostException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         recive.setText(e.toString());
     }

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

ServerSocket ss = new ServerSocket(8000);
Socket s = ss.accept();
BufferedReader input = new BufferedReader (new InputStreamReader (s.getInputStream ()));
while (true)
 {
     String st = "";
try
{
    st = input.readLine ();
    System.out.println (st);
}
catch (IOException e)
 {
    //error ("System: " + "Connection to server lost!");
    System.exit (1);
    break;
  }
 }
 ss.close();