1

我为 Android 创建了一个小型服务器客户端程序。除了一件事,它就像魅力一样工作。文件传输的第一个会话没有任何问题,但是当我尝试发送另一个文件时,如果不重新启动我的套接字连接,我就无法做到这一点。我想实现这一点: 1. 启动 Android 服务器 2. 连接远程客户端 3. 在同一个会话中传输任意数量的文件(无需重新启动服务器和重新连接客户端) 怎么做?任何帮助,将不胜感激!这是我的代码片段:服务器端方法:

public void initializeServer() {
    try {
        serverSocket = new ServerSocket(4444);
        runOnUiThread( new Runnable() {
              @Override
              public void run() {
                  registerLog("Server started successfully at: "+ getLocalIpAddress());
                  registerLog("Listening on port: 4444");
                  registerLog("Waiting for client request . . .");
              }
            });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("Listen failed", "Couldn't listen to port 4444");
    }

    try {
           socket = serverSocket.accept();
           runOnUiThread( new Runnable() {
                  @Override
                  public void run() {
                      registerLog("Client connected: "+socket.getInetAddress());
                  }
                });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("Acceptance failed", "Couldn't accept client socket connection");
    }
}

向客户端发送文件:

public void sendFileDOS() throws FileNotFoundException {
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              registerLog("Sending. . . Please wait. . .");
          }
        });
    final long startTime = System.currentTimeMillis();
    final File myFile= new File(filePath); //sdcard/DCIM.JPG
    byte[] mybytearray = new byte[(int) myFile.length()];
    FileInputStream fis = new FileInputStream(myFile);  
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
        OutputStream os = socket.getOutputStream();
        //Sending file name and file size to the server  
        DataOutputStream dos = new DataOutputStream(os);     
        dos.writeUTF(myFile.getName());     
        dos.writeLong(mybytearray.length);     
        dos.write(mybytearray, 0, mybytearray.length);     
        dos.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              long estimatedTime = (System.currentTimeMillis() - startTime)/1000;
              registerLog("File successfully sent");
              registerLog("File size: "+myFile.length()/1000+" KBytes");
              registerLog("Elapsed time: "+estimatedTime+" sec. (approx)");
              registerLog("Server stopped. Please restart for another session.");
          }
        });
}

客户端(在 PC 上运行):

public class myFileClient {
final static String servAdd="10.142.198.127";
static String filename=null;
static Socket socket = null;
static Boolean flag=true;

/**
 * @param args
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    initializeClient();
    receiveDOS();       
}
public static void initializeClient () throws IOException {
    InetAddress serverIP=InetAddress.getByName(servAdd);
    socket=new Socket(serverIP, 4444);
}
public static void receiveDOS() {
    int bytesRead;
    InputStream in;
    int bufferSize=0;

    try {
        bufferSize=socket.getReceiveBufferSize();
        in=socket.getInputStream();
        DataInputStream clientData = new DataInputStream(in);
        String fileName = clientData.readUTF();
        System.out.println(fileName);
        OutputStream output = new FileOutputStream("//home//evinish//Documents//Android//Received files//"+ fileName);
        long size = clientData.readLong();
        byte[] buffer = new byte[bufferSize];
        while (size > 0
                && (bytesRead = clientData.read(buffer, 0,
                        (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
4

1 回答 1

1

尝试冲洗后

output.write(buffer, 0, bytesRead);

如果这仍然不起作用,我发现我的服务器/客户端最适合您以下列方式使用的 objectoutputstreams。

oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());

// always call flush and reset after sending anything
oos.writeObject(server.getPartyMembersNames());
oos.flush();
oos.reset();

YourObject blah = (YourObject) ois.readObject();
于 2013-06-23T16:34:07.250 回答