能够通过套接字发送图像,但不能发送文本文件

我的客户端可以正常将图像发送到服务器,但是当涉及到文本文件时,它们会空着。 任何想法我做错了什么? 我真的很感激帮助,因为我一直试图让这项工作工作很多天。 谢谢。

这是服务器代码:

class TheServer { public void setUp() throws IOException { // this method is called from Main class. ServerSocket serverSocket = new ServerSocket(1991); System.out.println("Server setup and listening..."); Socket connection = serverSocket.accept(); System.out.println("Client connect"); System.out.println("Socket is closed = " + serverSocket.isClosed()); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str = rd.readLine(); System.out.println("Recieved: " + str); rd.close(); InputStream is = connection.getInputStream(); int bufferSize = connection.getReceiveBufferSize(); FileOutputStream fos = new FileOutputStream("C:/" + str); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] bytes = new byte[bufferSize]; int count; while ((count = is.read(bytes)) > 0) { bos.write(bytes, 0, count); } bos.flush(); bos.close(); is.close(); connection.close(); serverSocket.close(); } } 

这是客户端代码:

 public class TheClient { public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class. Socket socket = null; String host = "127.0.0.1"; socket = new Socket(host, 1991); // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("File is too large."); } BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); wr.write(file.getName()); wr.newLine(); wr.flush(); byte[] bytes = new byte[(int) length]; FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); int count; while ((count = bis.read(bytes)) > 0) { out.write(bytes, 0, count); } out.flush(); out.close(); fis.close(); bis.close(); socket.close(); } } 

  1. 在读取所有数据之前,您在服务器端过早关闭BufferedReader 。 这基本上关闭了连接。
  2. 不应将ReaderWriter用于二进制图像数据等非字符流。 并且您不应该将BufferedReader与任何其他流包装器混合用于相同的流,因为它可以读取与填充缓冲区一样多的数据。