这是我的第一个问题。我搜索了几个小时来帮助自己,但互联网上没有解决方案。我的程序只会在我插入“System.out.println()”时运行,我想使用 tcp 传输一个大文件(mp3,5Mb)。我有很多使用 java 的经验,但这是一个非常有趣的失败。
服务器和客户端位于 128.0.0.1
这是我的客户代码
public void receive(int port) {
try {
ServerSocket s = new ServerSocket(port);
Socket socket = s.accept();
BufferedInputStream in = new BufferedInputStream(
socket.getInputStream());
FileOutputStream fileOut = new FileOutputStream("dateiname.mp3");
startzeit = Calendar.getInstance().getTimeInMillis();
byte[] b = new byte[32];
while (in.available() > 0) {
System.out.println(Calendar.getInstance().getTimeInMillis()
- startzeit);
in.read(b);
fileOut.write(b);
fileOut.flush();
received += 1;
}
System.out.println("Feritg");
fileOut.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
和服务器
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class FileTransfer {
@SuppressWarnings("resource")
public static void send(File datei, InetAddress ip, int port)
throws IOException
{
Socket socket = new Socket(ip, port);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
FileInputStream fileIn = new FileInputStream(datei);
while (fileIn.available() > 0) {
byte[] b = new byte[32];
fileIn.read(b);
out.write(b);
out.flush();
}
out.close();
socket.close();
}
}
至少是服务器抛出的异常
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at FileTransfer.send(FileTransfer.java:20)
at MainServer.main(MainServer.java:12)
请帮我!