我正在使用 Java TCP socket: data transfer is slow 中的代码,效果很好,但我在接收部分遇到一个问题,它读取数据但不退出 while 循环,不知道为什么,代码完全相同。
好的,代码就像这个客户端:
uploadFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
try{
JFileChooser chooser = new JFileChooser();
File file=null;
int returnVal = chooser.showOpenDialog(UserWindow.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
file = chooser.getSelectedFile();
FileInputStream fis = new FileInputStream(file);
OutputStream os= Client.socket.getOutputStream();
int packetSize=65536;
byte[] buffer = new byte[packetSize];
Client.out.writeObject("upload file");
int read=0;
do{
os.write(buffer, 0, read);
System.out.println(read);
}while((read = fis.read(buffer))!=-1);
os.flush();
System.out.println("sent");
fis.close();
}
catch(Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(null,"File send error: "+ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);}
}
});
服务器端:
else if(message.equals("upload file")){
try{
FileOutputStream fos=new FileOutputStream("doc.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int packetsize=65536;
byte[] buffer = new byte[packetsize];
InputStream is =socket.getInputStream();
int read=0;
do{
bos.write(buffer,0,read);
System.out.println(read);
}while((read = is.read(buffer))!=-1);
System.out.println("received");
bos.close();
fos.close();
}catch(Exception ex){ex.printStackTrace();}
}
最佳答案
在您向其发送所需的数据之前,客户端代码不会结束(正如您链接的问题的提问者所说,数据很多)。
并且,您链接的问题的提问者的代码不完整,请发布您的完整代码。
关于Java文件传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145951/