UDP传输图片的尝试

来源:互联网 发布:翦伯赞中国史纲要知乎 编辑:程序博客网 时间:2024/05/12 23:30
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 blocke1.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();}}


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

原创粉丝点击