我正在尝试实现UDP客户端服务器。客户端使用rdt_send函数发送1032个字节,但服务器仅在客户端执行两次后才接收此数据包。
以下是代码:
rdt_send:
public void rdt_send(byte[] buffer, Integer mss, DatagramSocket s,Integer seqNum) throws IOException
{
int i,j,k;
byte[] seq_num = new byte[4];
byte[] seqnum_temp = new byte[4];
byte [] checksum = new byte[2];
byte [] udp_field = new BigInteger("0101010101010101",2).toByteArray();
Integer checksum_value = (int)calculateChecksum(buffer);
checksum = new BigInteger(checksum_value.toString(), 10).toByteArray();
seqnum_temp = new BigInteger(seqNum.toString(),10).toByteArray();
System.out.println(checksum_value);
Integer length_temp = seqnum_temp.length;
if (seqnum_temp.length<4)
{
Integer append = 4 -seqnum_temp.length;
for (i=0;i<append;i++)
{
seq_num[i] = 0;
}
for (j = append, k=0 ; j<4 && k<length_temp ; j++,k++)
{
seq_num[j] = seqnum_temp[k];
}
System.out.println(seq_num[0]);
}
byte[] finalSend = new byte[mss+8];
for (i=0;i<4;i++)
{
finalSend[i] = seq_num[i];
}
for (i=4,k=0;i<6 && k<2;i++,k++)
{
finalSend[i] = checksum[k];
}
for (i=6,k=0;i<8 && k<2 ;i++,k++)
{
finalSend[i] = udp_field[k];
}
for (i=8,k=0;i<finalSend.length && k< buffer.length;i++,k++)
{
finalSend[i] = buffer[k];
}
for (i=0;i<finalSend.length;i++)
{
System.out.println(finalSend[i]);
}
System.out.println("Got to final sending stage");
DatagramPacket p = new DatagramPacket (finalSend,finalSend.length,InetAddress.getLocalHost(),7771);
s.send(p);
System.out.println("Sent datagram");
}
客户:
package simpleFTP;
public class SimpleFTPClient {
public static void main(String args[]) throws IOException{
Integer seq_num =512;
Utils u = new Utils();
DatagramSocket d = new DatagramSocket();
File f =new File("C:/Users/amoolp/Desktop/client3/3333.txt");
FileInputStream fs = new FileInputStream(f);
byte[] bytesRead = new byte[1024];
fs.read(bytesRead,0,1024);
//DatagramPacket p = new DatagramPacket (bytesRead,bytesRead.length,InetAddress.getLocalHost(),7771);
// d.send(p);
u.rdt_send(bytesRead,1024,d,seq_num);
}
}
服务器:
public class Server {
public static void main (String args[]) throws IOException
{
DatagramSocket dg = new DatagramSocket (7771);
byte[] buf = new byte[1032];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("Waiting to receive packet");
dg.receive(packet);
System.out.println("Received packet");
for (int i=0; i<buf.length ; i++)
{
System.out.println(buf[i]);
}
}
}
有关为何发生这种情况的任何想法?
答案 0 :(得分:-1)
这是由缓冲区造成的。发送数据包后刷新()套接字。