我想實現一個UDP客戶端服務器。客戶端使用rdt_send函數發送1032個字節,但服務器僅在客戶端執行兩次後才接收此數據包。UDP套接字發送和接收
下面是代碼:
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]);
}
}
}
任何想法,爲什麼發生這種情況?
每次都適用於我,但您應該在退出之前關閉客戶端中的'DatagramSocket'。 – EJP