简体   繁体   English

通过套接字发送图像,结果为0KB

[英]Sending Image Over Socket, result 0KB

I have written a socket-based Android-to-server app for sending images. 我已经编写了基于套接字的Android到服务器应用程序来发送图像。 Here is what I have succeed with so far: the socket is connecting, the image is being sent, but that's it. 到目前为止,这是我已经成功完成的事情:套接字正在连接,图像正在发送,仅此而已。 It remains being sent and I see the file on my server-side with 0kb, and the sending never ends. 它仍然被发送,我在服务器端看到的文件为0kb,并且发送永无止境。

I'm sending a 233kb JPEG image over it. 我正在发送233kb JPEG图像。

Here is the client side: 这是客户端:

public class AccountCreator extends Activity {


private String serverIpAddress = "10.0.2.2";

private boolean connected = false;

private Handler handler = new Handler();

private Socket socket;

private Button sendimage;
//private ImageView profile;

private byte [] imgbyte;
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mes_registerpage);


sendimage = (Button) findViewById(R.id.sendpic);
ImageView imv = (ImageView)findViewById(R.id.imageView1);
sendimage.setOnClickListener(connectListener);
filepath = "storage/sdcard/autumn.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
     try {
         fis = new FileInputStream(imagefile);
     } catch (FileNotFoundException e) {
         System.out.println("file not found");
         e.printStackTrace();
     }

 Bitmap bm = BitmapFactory.decodeStream(fis);
 imgbyte = getBytesFromBitmap(bm);
 imv.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(serverIpAddress,1500);
        connected = true;
        while (connected==true) {
            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();
}
}

And here is the server code: 这是服务器代码:

public Server(int port) {

    this(port, null);
}

public Server(int port, ServerGUI sg) {

    this.sg = sg;

    this.port = port;

    sdf = new SimpleDateFormat("HH:mm:ss");

    al = new ArrayList<ClientThread>();
}

public void start() throws InterruptedException {
    keepGoing = true;
    try 
    {

        // the socket used by the server
        ServerSocket serverSocket = new ServerSocket(port);

        // infinite loop to wait for connections
        while(keepGoing) 
        {
            // format message saying we are waiting
            display("Server waiting for Clients on port " + port +  
".");

            Socket socket = serverSocket.accept();      
            // if I was asked to stop

            if(!keepGoing)
                break;
            ClientThread t = new ClientThread(socket);  
            jobdone=false;


     al.add(t);                                 
            t.start();
        }
        // I was asked to stop
        try {
            serverSocket.close();
            for(int i = 0; i < al.size(); ++i) {
                ClientThread tc = al.get(i);
                try {
                tc.sInput.close();
                tc.sOutput.close();
                tc.socket.close();
                }
                catch(IOException ioE) {
                    // not much I can do
                }
            }
        }
        catch(Exception e) {
            display("Exception closing the server and clients: " + e);
        }
    }
    // something went bad
    catch (IOException e) {
        String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + 
"\n";
        display(msg);
    }
}       
/*
 * For the GUI to stop the server
 */
protected void stop() {
    keepGoing = false;
    // connect to myself as Client to exit statement 
    // Socket socket = serverSocket.accept();
    try {
        new Socket("10.0.2.2",1500);
    }
    catch(Exception e) {
        // nothing I can really do
    }
}
/*
 * Display an event (not a message) to the console or the GUI
 */
private void display(String msg) {
    String time = sdf.format(new Date()) + " " + msg;
    if(sg == null)
        System.out.println(time);
    else
        sg.appendEvent(time + "\n");
}

    // create a server object and start it



 public static void shutdown() {
jobdone = true;


}
/** One instance of this thread will run for each client */

   class ClientThread extends Thread {
    // the socket where to listen/talk
    String Type;
    Socket socket;
    InputStream sInput;
    ObjectOutputStream sOutput;
    // my unique id (easier for deconnection)
    int id;



    // Constructore
    ClientThread(Socket socket) throws InterruptedException, IOException {
        // a unique id
        id = ++uniqueId;
        this.socket = socket;
        /* Creating both Data Stream */
        System.out.println("Thread trying to create Object Input/Output  
 Streams");

            // create output first
        int bytesRead;
        int current = 0;
        int filesize=65383; 
        byte [] mybytearray2  = new byte [filesize];

        try {
            InputStream is = socket.getInputStream();
            System.out.println("receiving");

            FileOutputStream fos = new FileOutputStream("D://IMG-   
 20130112-WA0011.jpeg");
         // destination path and name of file

        BufferedOutputStream bos = new BufferedOutputStream(fos);

            bytesRead = is.read(mybytearray2,0,mybytearray2.length);

        current = bytesRead;



           try {
            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();
           }
           }finally{

           }

           }finally{
               }
           }


        }  








    // what will run forever

        // remove myself from the arrayList containing the list of the
        // connected Clients
    public void main(String[] args) throws InterruptedException {
        // start server on port 1500 unless a PortNumber is specified 
        int portNumber = 1500;
        switch(args.length) {
            case 1:
                try {
                    portNumber = Integer.parseInt(args[0]);
                }
                catch(Exception e) {
                    System.out.println("Invalid port number.");
                    System.out.println("Usage is: > java  
Server [portNumber]");
                    return;
                }
            case 0:
                break;
            default:
                System.out.println("Usage is: > java Server   
 [portNumber]");
                return;

        }
        // create a server object and start it
        Server server = new Server(portNumber);
        server.start();
    }

}

Do you guys know what is wrong? 你们知道发生什么事了吗?

int filesize=65383; 
byte [] mybytearray2  = new byte [filesize];

You don't know the filesize at forehand. 您不知道正手的文件大小。 Moreover you send a file of 233kB and trying to read all in mybytearray2 will give you a bufferoverflow and your server will crash. 此外,您发送了一个233kB的文件,尝试读取mybytearray2中的所有文件将给您带来缓冲区溢出,并且服务器将崩溃。 By the way: from where did you get/copy this code? 顺便说一句:您从哪里获得/复制此代码? I saw it before. 我以前看过 I'ts no good. 这不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM