Android-通过套接字编程发送图像 [英] Android - Send an image through socket programming

查看:70
本文介绍了Android-通过套接字编程发送图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个套接字应用程序,其中一个电话将成为客户端,而另一部电话将成为服务器.该程序能够使用打印书写器从客户端向服务器发送字符串,但是当我尝试发送图像文件时,它将引发异常.如果有人可以帮助我,我将非常感激.

I am implementing a socket application where one phone will be a client and the other will be a server. The program is able to send strings using print writer just fine from the client to the sever but when i try to send an image file, it throws an exception. I'd really appreciate if someone could help me out.

这是服务器的代码

public class ServerActivity extends Activity {

private TextView serverStatus;
private ImageView profile;

// 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);
    profile = (ImageView) findViewById(R.id.image);

    String filepath = "/sdcard/DCIM/time table.png";
    File imagefile = new File(filepath);
    FileInputStream fis = null;
         try {
             fis = new FileInputStream(imagefile);
         } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }

     Bitmap bm = BitmapFactory.decodeStream(fis);
     profile.setImageBitmap(bm);

    SERVERIP = getLocalIpAddress();

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

public class ServerThread implements Runnable {
    //String line;
    byte [] line;
    Bitmap bitmap;
    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.");
                        }
                    });

                    try {
                        /*InputStream in = client.getInputStream();
                        line = null;
                        in.read(line);

                            Log.d("ServerActivity", line.toString());
                            bitmap = BitmapFactory.decodeByteArray(line , 0, line.length);*/
                        int bytesRead;
                        int current = 0;
                        int filesize=65383; 
                        byte [] mybytearray2  = new byte [filesize];
                        InputStream is = client.getInputStream();
                        FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/IMG-20130112-WA0011.jpeg"); // destination path and name of file
                        //FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
                        BufferedOutputStream bos = new BufferedOutputStream(fos);
                        bytesRead = is.read(mybytearray2,0,mybytearray2.length);
                        current = bytesRead;


                        do {
                           bytesRead =
                              is.read(mybytearray2, current, (mybytearray2.length-current));
                           if(bytesRead >= 0) current += bytesRead;
                        } while(bytesRead > -1);

                        bos.write(mybytearray2, 0 , current);
                        bos.flush();
                        long end = System.currentTimeMillis();
                        //System.out.println(end-start);
                        bos.close();


                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    profile.setImageBitmap(bitmap);

                                    //serverStatus.setText(line);
                                }
                            });

                        /*BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                        line = null;
                        while ((line = in.readLine()) != null) {
                            Log.d("ServerActivity", line);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    serverStatus.setText(line);
                                    // DO WHATEVER YOU WANT TO THE FRONT END
                                    // THIS IS WHERE YOU CAN BE CREATIVE
                                }
                            });
                        }*/
                        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 {

private EditText serverIp;

private Button connectPhones;

private String serverIpAddress = "";

private boolean connected = false;

private Handler handler = new Handler();

private Socket socket;

private ImageView profile;

private byte [] imgbyte;
String filepath;
@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);
    profile = (ImageView) findViewById(R.id.imageView1);

    filepath = "/sdcard/small.jpg";
    File imagefile = new File(filepath);
    FileInputStream fis = null;
         try {
             fis = new FileInputStream(imagefile);
         } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }

     Bitmap bm = BitmapFactory.decodeStream(fis);
     imgbyte = getBytesFromBitmap(bm);
     profile.setImageBitmap(bm);
}

private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        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 = new Socket(serverAddr, ServerActivity.SERVERPORT);
            connected = true;
            while (connected) {
                try {


                    /*File myFile = new File (filepath); 
                    byte [] mybytearray  = new byte [(int)myFile.length()];
                    FileInputStream fis = new FileInputStream(myFile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    OutputStream os = socket.getOutputStream();
                    Log.d("ClientActivity", "C: Sending command.");
                    //System.out.println("Sending...");
                    os.write(mybytearray,0,mybytearray.length);
                    os.flush();*/

                    Log.d("ClientActivity", "C: Sending command.");
                    /*PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);*/
                        // WHERE YOU ISSUE THE COMMANDS

                    OutputStream output = socket.getOutputStream();
                    Log.d("ClientActivity", "C: image writing.");
                    output.write(imgbyte);
                    output.flush();
                       // out.println("Hey Server!");
                        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;
        }
    }
}

protected void onStop() {
    super.onStop();
    try {
         // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
         socket.close();
         connected = false;
     } catch (IOException e) {
         e.printStackTrace();
     }
}

public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

}

更新: 服务器端代码抛出异常.它的异常显示为:糟糕.连接中断.请重新连接手机." 这是抛出的异常: java.lang.RuntimeException:无法在尚未调用Looper.prepare()的线程内创建处理程序

update: The exception is thrown at the server side code. Its the exception which reads :"Oops. Connection interrupted. Please reconnect your phones." This is the exception that is thrown: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

推荐答案

谢谢大家,我发现了错误. 敬酒消息必须位于UI线程或处理程序内.由于我在非UI线程中有其中一些,所以它开始引发异常.

Thanks everyone , I found the error. The toast messages have to be inside the UI thread or the handler . As I had a few of them in a non UI thread, it began to throw the exception.

这篇关于Android-通过套接字编程发送图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆