使用java套接字发送文件
我在这里发送来自两个java应用程序的文件,即服务器和客户端的源代码使用java套接字发送文件,java,sockets,Java,Sockets,我在这里发送来自两个java应用程序的文件,即服务器和客户端的源代码 public class FileClient { private Socket s; public FileClient(String host, int port, String file) { try { s = new Socket(host, port); sendFile(file); } catch (Except
public class FileClient {
private Socket s;
public FileClient(String host, int port, String file) {
try {
s = new Socket(host, port);
sendFile(file);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile(String file) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while ((fis.read(buffer) > 0)) {
dos.write(buffer);
}
fis.close();
dos.close();
}
public static void main(String[] args) {
FileClient fc = new FileClient("192.168.0.167", 1988, "C:/Users/mhattabi/Desktop/fileData.txt");
}
}
这里是服务器的源代码
public class FileServer extends Thread {
private ServerSocket ss;
public FileServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket clientSock = ss.accept();
saveFile(clientSock);
// ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream("fileData.txt");
byte[] buffer = new byte[4096];
int filesize = 15123; // Send file size in separate msg
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = dis.read(buffer)) > 0) {
totalRead += read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
dis.close();
}
public static void main(String[] args) {
FileServer fs = new FileServer(1988);
fs.start();
}
}
问题是,在服务器中我收到了文件,但其中有额外的字符。如有任何帮助,将不胜感激。谢谢
我认为额外的角色来自这个地方;每次写入4096字节
,最后一次它发生在小于4096字节的地方。然后您会得到额外的字符,这是常见的问题
while ((fis.read(buffer) > 0)) {
dos.write(buffer);
}
您忽略读取返回的计数,并假设它已填充缓冲区。应该是:
while ((count = fis.read(buffer) > 0)) {
dos.write(buffer, 0, count);
}
奇怪的是,您在服务器中拥有此权限。注意:这里不需要DataOutputStream。它不是“来自这个地方”。您的思路是正确的,但是您错误地识别了错误站点,并且没有提供实际的解决方案。
while ((count = fis.read(buffer) > 0)) {
dos.write(buffer, 0, count);
}