如何使用TCP套接字传输位图

时间:2012-04-13 17:49:26

标签: android client-server tcpclient tcpserver tcpsocket

我有一个服务器/客户端应用程序,我想在客户端上发送和显示服务器的屏幕截图。任何身体都可以帮助我。感谢

代码如下

服务器端

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 个答案:

答案 0 :(得分:4)

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

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

在服务器端接收器中使用bytearray,然后以这种方式重新调整位图:

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