2012-04-13 60 views
1

我有一个服务器/客户端应用程序,我想在其中发送并在客户端上显示服务器的屏幕截图。任何身体都可以帮助我。感谢如何使用TCP套接字传输位图

的代码如下

服务器端

public class ServerActivity extends Activity { 

private TextView serverStatus; 
RelativeLayout mainLayout; 


// default ip 
public static String SERVERIP = "10.0.2.15"; 

// designate a port 
public static final int SERVERPORT = 8080; 

private Handler handler = new Handler(); 

private ServerSocket serverSocket; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.server); 
    serverStatus = (TextView) findViewById(R.id.server_status); 


    SERVERIP = getLocalIpAddress(); 

    Thread fst = new Thread(new ServerThread()); 
    fst.start(); 
} 

public class ServerThread implements Runnable { 

    public void run() { 
     try { 
      if (SERVERIP != null) { 
       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         serverStatus.setText("Listening on IP: " + SERVERIP); 
        } 
       }); 
       serverSocket = new ServerSocket(SERVERPORT); 

       while (true) { 
       // listen for incoming clients 
        Socket client = serverSocket.accept(); 
        handler.post(new Runnable() { 
         @Override 
         public void run() { 
          serverStatus.setText("Connected");     
         mainLayout = (RelativeLayout)findViewById(R.id.screen); 
          ImageView iv =(ImageView)findViewById(R.id.iv); 
          File root = Environment.getExternalStorageDirectory(); 
          File file = new File(root,"androidlife.jpg"); 
        Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(), mainLayout 
         .getHeight(), Bitmap.Config.ARGB_8888); 
        iv.setImageBitmap(b); 
        Canvas c = new Canvas(b); 
        mainLayout.draw(c); 

          //serverStatus.setText("Screenshot is displaying"); 
         } 
        }); 

        try { 


         BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
         BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); 
         //receive a message 
         String incomingMsg = in.readLine() + System.getProperty("line.separator"); 
         Log.i("TcpServer", "received: " + incomingMsg); 
         serverStatus.setText("received: " + incomingMsg); 
         //send a message 
         String outgoingMsg = "goodbye from port " + SERVERPORT + System.getProperty("line.separator"); 
         out.write(outgoingMsg); 
         //out.flush(); 
         Log.i("TcpServer", "sent: " + outgoingMsg); 
         serverStatus.setText("sent: " + outgoingMsg); 
         //while ((line = in.readLine()) != null)  
          handler.post(new Runnable() { 
           @Override 
           public void run() { 


           } 
          }); 
         // } 
         break; 
        } 
         catch (Exception e) { 
         handler.post(new Runnable() { 
          @Override 
          public void run() { 
           serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones."); 
          } 
         }); 
         e.printStackTrace(); 
        } 
       } 
      } else { 
       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         serverStatus.setText("Couldn't detect internet connection."); 
        } 
       }); 
      } 
     } catch (Exception e) { 
      handler.post(new Runnable() { 
       @Override 
       public void run() { 
        serverStatus.setText("Error"); 
       } 
      }); 
      e.printStackTrace(); 
     } 
    } 
} 

// gets the ip address of your phone's network 
private String getLocalIpAddress() { 
    try { 
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
      NetworkInterface intf = en.nextElement(); 
      for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
       InetAddress inetAddress = enumIpAddr.nextElement(); 
       if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } 
      } 
     } 
    } catch (SocketException ex) { 
     Log.e("ServerActivity", ex.toString()); 
    } 
    return null; 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    try { 
     // make sure you close the socket upon exiting 
     serverSocket.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 

客户端代码:

public class ClientActivity extends Activity { 

public EditText serverIp; 
public TextView tv; 

private Button connectPhones; 

private String serverIpAddress = ""; 
private static final int SERVERPORT = 8080; 

private boolean connected = false; 

//private Handler handler = new Handler(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.client); 

    serverIp = (EditText) findViewById(R.id.server_ip); 
    connectPhones = (Button) findViewById(R.id.connect_phones); 
    connectPhones.setOnClickListener(connectListener); 
} 


private OnClickListener connectListener = new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     // if(true) 
     if (!connected) { 
      serverIpAddress = serverIp.getText().toString(); 
      if (!serverIpAddress.equals("")) { 
       Thread cThread = new Thread(new ClientThread()); 
       cThread.start(); 
      } 
     } 
    } 
}; 

public class ClientThread implements Runnable { 

    public void run() { 
     try { 
      InetAddress serverAddr = InetAddress.getByName(serverIpAddress); 
      Log.d("ClientActivity", "C: Connecting..."); 
      Socket socket = new Socket(serverAddr, SERVERPORT); 
      connected = true; 
      while (connected) { 
       try { 
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
        //send output msg 
        String outMsg = "TCP connecting to " + SERVERPORT + System.getProperty("line.separator"); 
        out.write(outMsg); 
        out.flush(); 
        Log.i("TcpClient", "sent: " + outMsg); 
        //accept server response 
        String inMsg = in.readLine() + System.getProperty("line.separator"); 
        tv.setText("message from server"+ inMsg); 
        Log.i("TcpClient", "received: " + inMsg); 
       // ImageView iv = (ImageView)findViewById(R.id.iv); 
        // iv.setImageBitmap(bm); 
         Log.d("ClientActivity", "C: Sent."); 
       } catch (Exception e) { 
        Log.e("ClientActivity", "S: Error", e); 
       } 
      } 
      socket.close(); 
      Log.d("ClientActivity", "C: Closed."); 
     } catch (Exception e) { 
      Log.e("ClientActivity", "C: Error", e); 
      connected = false; 
     } 
    } 
    } 
} 
+1

你需要更具体。有没有错误,或者你不知道如何完成某项任务?如果您提供有关该问题的更多详细信息,我们将很乐意为您提供帮助。 – Shellum 2012-04-13 17:53:08

回答

3

我没有在你的代码中看到哪里哪里,你要发送图像或屏幕截图的位图!你不能发送通过套接字发送一个位图,你应该在发送方添加此创建位图b。创作的字节数组出位图后:

   ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
       b.compress(Bitmap.CompressFormat.PNG, 100, stream); 
       byte[] byteArray = stream.toByteArray(); 

在服务器端接收的字节组,然后recreat的bitmap用这种方式:

   Bitmap breceived = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
+1

不应该首先发送由位图创建的byteArray的长度吗? – zoska 2014-05-07 06:11:25