将文件发送到服务器并在客户端tcp java上接收它

时间:2014-01-12 15:34:32

标签: java sockets tcp network-programming

1.client将文件成功发送到服务器

2.server成功接收文件

但是 3.当服务器尝试将此文件发送回客户端后,处理收到的文件(由客户端发送)后发生错误:

插座:空

连接已关闭

这是将文件方法发送回客户端

“服务器代码:”

public void sendFileBack(String fileName)
throws UnknownHostException,FileNotFoundException, IOException {
  Socket sock = new Socket("192.168.0.103", 13267);
  String tmpName=fName.replace(".mcrl2", ".lps");
  File myFile = new File("out" + "\\" +tmpName );
  byte[] mybytearray = new byte[(int) myFile.length()];
  FileInputStream fis = new FileInputStream(myFile);
  BufferedInputStream bis = new BufferedInputStream(fis);
  //bis.read(mybytearray, 0, mybytearray.length);  

  DataInputStream dis = new DataInputStream(bis);
  dis.readFully(mybytearray, 0, mybytearray.length);
  OutputStream os = sock.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();

  //Sending file data to the server  
  os.write(mybytearray, 0, mybytearray.length);
  os.flush();
  console.append("\n\n Output file transfered successfully \n \n");


  //Closing socket  
  sock.close();
}

这是从服务器接收文件方法

“客户端代码:”

private void receiveFileBack() throws IOException {

  int bytesRead;
  int port; 

  ServerSocket serverSocket = null;
  serverSocket = new ServerSocket(4444);
  while (true) {
    Socket clientSocket = serverSocket.accept();
    System.out.print("accepted connection"+clientSocket);

    InputStream in = clientSocket.getInputStream();
    DataInputStream clientData = new DataInputStream(in);

    String fileName = clientData.readUTF();
    System.out.print(fileName+"..........");

    File f =new File("serverOut\\"+fileName);
    OutputStream output = new FileOutputStream("serverOut\\"+fileName);

    long size = clientData.readLong();
    byte[] buffer = new byte[1024];

    while (size > 0 && 
           (bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
      serverStatus.append("Reading file..\n");
      output.write(buffer, 0, bytesRead);

      size -= bytesRead;
    }

    // Closing the FileOutputStream handle  
    output.close();
    output.flush();
  }
}

0 个答案:

没有答案