[原创]JAVA实现tftp服务端 -- WRQ
这里是WRQ请求的处理代码:
=================================================
文章在博客中的地址: http://blog.bc-cn.net/user1/37/archives/2007/5202.shtml
=================================================
tftpClientAgent.java=====================================
public void WRQ() {
int ntimeout = this.m_MAX_nTimeOut;
try {
short nblock = 0;
//send the #0 block ACK to start the transfer
this.SendACK(nblock++);
//wait for the data packet
while (ntimeout > 0) {
DatagramPacket dp;
dp = this.waitForData();
//dp = new DatagramPacket(buf, 516);
if (dp == null) {
//this.SendERROR((short)0, "超时了,连接被服务器断开 ...");
//System.out.println("debug: tftpClientagent.WRQ() --> timeout: " + ntimeout);
ntimeout--;
} else {
//ok, get a packet, check the ip and port
if (!((dp.getAddress().equals(this.m_ClientAddress))
&& (dp.getPort() == this.m_ClientPort))) {
//ip or port has a mistake
//this.SendERROR((short)0, "我不认识你");
//System.out.println("debug: ip or port error ...");
ntimeout--;
} else { //right ip and port
//get the opcode
DataInputStream din = new DataInputStream(new ByteArrayInputStream(dp.getData()));
int opcode = din.readShort();
//System.out.println("debug: the opcode is " + opcode);
if (opcode != 3) {
//不是03号data包
if (opcode == 2 && nblock == 1) {
//是02号WRQ包,且正在等待#1号data包
//此时收到WRQ,说明#0号ACK有可能失败了,重发
this.SendACK((short)(nblock-1));
} else {
this.SendERROR((short)4, "非法的TFTP操作");
}
ntimeout--;
} else { //data packet
//System.out.println("debug: get a data packet");
int nblk = din.readShort();
//System.out.println("debug: the waiting for #" + nblock + " -- the curBlock is #" + nblk);
if (nblk != nblock) {
//System.out.println("debug: re-SendACK(" + (nblock-1) + ")");
//不是期待的块号,重发上一个包的ACK,超时计数减1
this.SendACK((short)(nblock-1));
ntimeout--;
} else { //the right packet waiting for
//this.SaveFile(this.m_filename);
if (!this.SaveFile(nblock, dp, this.m_filename, this.m_mode)) {
ntimeout = 0;
this.SendERROR((short)3, "磁盘满或超过分配的配额");
} else {
//send the current block ACK
this.SendACK(nblock);
//System.out.println("debug: dp.length = " + (dp.getLength()-4));
if (dp.getLength()-4 >= 512) {
//the transfer isn't ended
nblock++; //wait for the next block
ntimeout = this.m_MAX_nTimeOut; //重置超时记数
} else {
//ok, there is no more data, the transfer succ
ntimeout = 1;
//continue wait for current block for 1 timeout,
//in case of the last ACK's failing
}
}
}
}
}
}
}
} catch (Exception e) {
//System.out.println("Exception in tftpClientAgent.WRQ() --> " + e.getLocalizedMessage());
}
}
======================================
好了,demo的代码大部分就在这里了。
以后继续努力,