Java - UDP sending data over socket.. not rec. all data

二次信任 提交于 2019-12-24 03:18:29

问题


It would seem that the Client - Server application i wrote does work however it seems that not all data is processed every time.

I am testing it on a local machine in Eclipse env.

Server:

    private void sendData() throws Exception
{
    DatagramPacket data = new DatagramPacket(outgoingData, outgoingData.length, clientAddress, clientPort);
    InputStream fis = new FileInputStream(responseData);

    int a;
    while((a = fis.read(outgoingData,0,512)) != -1)
    {
        serverSocket.send(data);
    }
}

Client:

    private void receiveData() throws Exception
{
    DatagramPacket receiveData = new DatagramPacket(incomingData, incomingData.length);
    OutputStream fos = new FileOutputStream(new File("1"+data));
    while(true)
    {
        clientSocket.receive(receiveData);
        fos.write(incomingData);
    }
}

I used to have if else in the while(true) loop to check if packet length is less than 512 bytes so it knew when to break;

I was thinking there was a problem whit that but seems that was oke for now i just wait few minutes and then stop the Client.java app

The file does transfer but the original file is 852kb and so far i got 777, 800, 850,.. but never all of it.


回答1:


The fundamental problem with your approach is that UDP does not guarantee delivery. If you have to use UDP (rather than, say, TCP), you have to implement a scheme that would detect and deal with packets that got lost, arrive out of order, or are delivered multiple times.

See When is it appropriate to use UDP instead of TCP?




回答2:


You should probably use TCP to transfer files. You are probably losing packets because you are sending them so fast in that while loop.

int a;
while((a = fis.read(outgoingData,0,512)) != -1)
{
   serverSocket.send(data);
}

since you're sending so fast I highly doubt it will have a chance to be received in the right order. some packets will probably be lost because of it too.

Also since your sending a fixed size of 512 bytes the last packet you send will probably not be exactly that size, so you will see the end of the file "look wierd."



来源:https://stackoverflow.com/questions/9589905/java-udp-sending-data-over-socket-not-rec-all-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!