UDP传输图片的尝试

 

 UDP是不可靠的,发送的数据不一定会到达,且顺序不一定完整。

想要验证一下UDP传输文件的效果,最直观的是传输图片。

这里在客户端的DatagramSocket设置了个超时时间,当发送端发送完后客户端就会抛出超时异常,程序就退出了。

UDPFileReceiver:

 

package com.woxiaoe.study.java_net.udp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPFileReceiver {
	private int port = 1220;
	private DatagramSocket socket;
	
	public UDPFileReceiver() throws SocketException{
		socket = new DatagramSocket(port);
		socket.setSoTimeout(4000);
	}
	public void reciveData() throws FileNotFoundException{
		File newfile = new File("641k.jpg");
		byte[] buf = new byte[8192];
		FileOutputStream fos = new FileOutputStream(newfile);
		while(true){
			DatagramPacket packet = new DatagramPacket(buf, 8192);
			try{
				socket.receive(packet);
				fos.write(packet.getData(), 0, packet.getLength());
			}catch(Exception e){
				try {
					System.out.println("传输结束");
					socket.close();
					fos.flush();
					fos.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				break;
			}
		}
	}
	public static void main(String[] args) throws FileNotFoundException, SocketException {
		new UDPFileReceiver().reciveData();
	}

}

 

 UDPFileServer:

 

package com.woxiaoe.study.java_net.udp;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPFileServer {
	private int port = 1220;
	private String filePath = "";
	private DatagramSocket socket;
	public UDPFileServer() throws SocketException {
		socket = new DatagramSocket();
		//System.out.println("服务器启动成功");
	}
	public void service() throws IOException{
		InputStream is = this.getClass().getResourceAsStream("641k.jpg");
		byte[] buffer = new byte[8192];
		int len = 0;
		while((len = is.read(buffer)) != -1){
			System.out.println(len);
			DatagramPacket packet = new DatagramPacket(buffer, len,InetAddress.getByName("localhost"),port);
			socket.send(packet);
		}
		socket.close();
	}
	public static void main(String[] args) throws SocketException, IOException {
		new UDPFileServer().service();
	}
}

 原图片 和 传输后的图片对比

 

 

(32K)


(100K)
 

 

 (900K)

 

 


通过比较可以看出但图片大小增大了以后失真就越明显,由此可见UDP传输不能保证文件的完整性。如果基于UDP的文传输要保证文件的完整性,者必须处理丢失或乱序的情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值