我在TFTP服务器上工作。根据图像,我的数据包的最大长度是516字节(2 + 2 + 512)。
我正在尝试从客户端datagrampacket获取原始长度(在这种情况下,在RRQ数据包中发送13个字节),而不是获取服务器datagrampacket长度(516字节),我保存客户端datagrampacket。
我需要提取文件名,我这样做但是字符串内容是“filename + nullBytes”,那些空字节来自服务器datagrampacket。
这是我陷入困境的代码:
public static short RRQ = 1;
enter code here
public void dataMetod() throws IOException{
byte[] packet = new byte[516];
//socket with listening port 5000
DatagramSocket datagramSocket = new DatagramSocket(5000);
//while receive packets
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(packet,packet.length);
datagramSocket.receive(datagramPacket);
System.out.println("server: new packet!!:");
//create a byte[] with the "received packet length"(that's not true)
byte[] inData = new byte[datagramPacket.getLength()];
inData = datagramPacket.getData();
System.out.println("length: "+inData.length);
byte code;
code = inData[1];
System.out.println(code);
//check if its an RRQ packet
if (code == RRQ) {
System.out.println("server: RRQ PACKET!!");
String fileName = this.getFileName(inData);
System.out.println(fileName);
}
public String getFileName(byte[] inData) {
byte[] aux = new byte[inData.length - 7];
for (int i = 0; i < aux.length; i++) {
aux[i] = inData[i + 2];
}
return new String(aux);
}
答案 0 :(得分:0)
试试这个:
public String getFileName(byte[] inData) {
final int maxLen = inData.length;
final StringBuilder sb = new StringBuilder();
int i = 2;
byte b;
while ( (i < maxLen) && (b = inData[i]) != 0 ) {
final int v = ((int)b) & 0xff;
sb.append( (char) v );
i++;
}
return sb.toString();
}
答案 1 :(得分:0)
我们可以通过在客户端类的fileName字符串中添加“\ n”,而不是获取接收数据包的原始长度(通过数组搜索文件名),然后使用BufferedReader来检测“\ n “并保存fileName。 代码:
public String getFileName(byte[] inData) throws IOException {
//get a sub-array, from index[2] (beacuse we dont want opCode) to inData length
byte[] b =Arrays.copyOfRange(inData, 2, inData.length);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
//We read a word that will be saved when "\n" is found.
//(adding "\n" previously to the fileName String in client class)
String filename = bf.readLine();
bf.close();
is.close();
System.out.println("server: filename is: "+filename.length()+" bytes");
return filename;
}