下面是更好的版本,其口吃了起來大文件到8K的塊。 將文件X寫入/ tmp/X。需要注意的是/home/bela/fast.xml配置必須被改變,當然,:
public class SimpleFileTransfer extends ReceiverAdapter {
protected String filename;
protected JChannel channel;
protected Map<String,OutputStream> files=new ConcurrentHashMap<>();
protected static final short ID=3500;
private void start(String name, String filename) throws Exception {
ClassConfigurator.add((short)3500, FileHeader.class);
this.filename=filename;
channel=new JChannel("/home/bela/fast.xml").name(name);
channel.setReceiver(this);
channel.connect("FileCluster");
eventLoop();
}
private void eventLoop() throws Exception {
while(true) {
Util.keyPress(String.format("<enter to send %s>\n", filename));
sendFile();
}
}
protected void sendFile() throws Exception {
FileInputStream in=new FileInputStream(filename);
try {
for(;;) {
byte[] buf=new byte[8096];
int bytes=in.read(buf);
if(bytes == -1)
break;
sendMessage(buf, 0, bytes, false);
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
sendMessage(null, 0, 0, true);
}
}
public void receive(Message msg) {
byte[] buf=msg.getRawBuffer();
FileHeader hdr=(FileHeader)msg.getHeader(ID);
if(hdr == null)
return;
OutputStream out=files.get(hdr.filename);
try {
if(out == null) {
File tmp=new File(hdr.filename);
String fname=tmp.getName();
fname="/tmp/" + fname;
out=new FileOutputStream(fname);
files.put(hdr.filename, out);
}
if(hdr.eof) {
Util.close(files.remove(hdr.filename));
}
else {
out.write(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
}
}
catch(Throwable t) {
System.err.println(t);
}
}
protected void sendMessage(byte[] buf, int offset, int length, boolean eof) throws Exception {
Message msg=new Message(null, buf, offset, length).putHeader(ID, new FileHeader(filename, eof));
// set this if the sender doesn't want to receive the file
// msg.setTransientFlag(Message.TransientFlag.DONT_LOOPBACK);
channel.send(msg);
}
protected static class FileHeader extends Header {
protected String filename;
protected boolean eof;
public FileHeader() {} // for de-serialization
public FileHeader(String filename, boolean eof) {
this.filename=filename;
this.eof=eof;
}
public int size() {
return Util.size(filename) + Global.BYTE_SIZE;
}
public void writeTo(DataOutput out) throws Exception {
Util.writeObject(filename, out);
out.writeBoolean(eof);
}
public void readFrom(DataInput in) throws Exception {
filename=(String)Util.readObject(in);
eof=in.readBoolean();
}
}
public static void main(String[] args) throws Exception {
if(args.length != 2) {
System.out.printf("%s <name> <filename>\n", SimpleFileTransfer.class.getSimpleName());
return;
}
new SimpleFileTransfer().start(args[0], args[1]); // name and file
}
}
這不是人們編寫代碼對你的站點。顯示你已經嘗試了什麼,然後人們會幫助你。 Downvoting。 –
@我們是博格,夠公平的。我用迄今爲止的嘗試更新了這個問題。 – avidProgrammer
@WeareBorg我認爲你提出了你的觀點,你不需要冷靜下來一個非常好的問題。 – kimathie