我使用的代码Java TCP socket: data transfer is slow,工作很好,但我有一个接收部分的问题,它读取的数据,但不退出while循环,不知道为什么,代码是完全一样的。Java文件传输
确定这样的代码是这样的客户端:
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();}
}
显示我们揭掉codez,宝贝。 – 2011-05-26 22:47:09