Java-UDP通过套接字发送数据.所有数据 [英] Java - UDP sending data over socket.. not rec. all data

查看:118
本文介绍了Java-UDP通过套接字发送数据.所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写的客户端-服务器"应用程序似乎可以正常工作,但是似乎并非每次都处理所有数据.

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

我正在Eclipse env的本地计算机上对其进行测试.

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

服务器:

    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);
    }
}

客户:

    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);
    }
}

我曾经在while(true)循环中使用if else来检查数据包长度是否小于512字节,以便知道何时中断;

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;

我以为是有问题的,但现在看来还可以,我只等了几分钟,然后停止Client.java应用程序

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

该文件确实可以传输,但原始文件为852kb,到目前为止,我获得了777、800、850....但从来没有全部.

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

推荐答案

您的方法的基本问题是UDP无法保证传递.如果必须使用UDP(而不是TCP),则必须实现一种方案,该方案可以检测和处理丢失,乱序或多次交付的数据包.

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.

请参见何时适合使用UDP代替TCP?

这篇关于Java-UDP通过套接字发送数据.所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆