我正在做一个客户端-服务器文件传输项目,我在 localhost 上几乎完成了我的测试,但是今天出现以下错误,这里是客户端和服务器的源代码:
客户端
public class Client {
public static void main(String args[]) {
String receiverIP = null;
int serverPort = 0;
receiverIP = args[0];
serverPort = Integer.parseInt(args[1]);
String fileToSend = args[2];
byte[] aByte = new byte[1];
int bytesR;
Socket clientSocket = null;
BufferedOutputStream bos = null;
InputStream is = null;
try {
clientSocket = new Socket(receiverIP, serverPort);
bos = new BufferedOutputStream(clientSocket.getOutputStream());
is = clientSocket.getInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
if (is != null) {
FileOutputStream fos = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
File myFile = new File( fileToSend );
System.out.println("The file chosen is being sent...");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream( myFile );
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, mybytearray.length);
bis.close();
return;
}catch (IOException ex) {
ex.printStackTrace();
}
File file = new File("C:\\copy.jpg");
fos = new FileOutputStream( file );
bos = new BufferedOutputStream(fos);
bytesR = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesR = is.read(aByte);
} while (bytesR != -1);
System.out.println("File transfer successful");
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
服务器端
public class Server {
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
BufferedOutputStream ToClient = null;
try {
welcomeSocket = new ServerSocket(3249);
System.out.println("The port " + welcomeSocket.getLocalPort() + " is opened and ready for use.");
Socket connectionSocket = welcomeSocket.accept();
ToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
这是我得到的错误
The file chosen is being sent...
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.write(Unknown Source)
at Client.main(Client.java:44)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at Client.main(Client.java:55)
我几乎可以肯定这个错误不是关于在传输所有数据之前关闭服务器套接字,也不是关于字节数组上的读写过程,但我所有的修复尝试都是徒劳的,也许我放错了流,所以它们没有按预期工作,(创建了 copy.jpg 文件但没有获得任何流)任何帮助将不胜感激
编辑:我忘了提,目前我正在使用无线互联网连接,并且我读过一些关于套接字编程的内容,其中提到无线网络测试不可靠