UDP实现多线程文件接收服务器

package udp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author aachen0
 * @date 2018/4/16 20:49
 * IDE:IntelliJ IDEA
 * UDP数据包传输实现文件上传
 */
public class Receiver implements Runnable{
    public static void main(String[] args) {
        new Thread(new Receiver()).start();
    }
    public static void accept() throws IOException {
        byte[] buff = new byte[1024];
        int length = 0;
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        DatagramPacket datagramPacket = new DatagramPacket(buff,buff.length);
        while (true) {
            datagramSocket.receive(datagramPacket);
            String fileSave = new String(buff, 0, datagramPacket.getLength());
            FileOutputStream fileOutputStream = new FileOutputStream(new File("service\\" + fileSave));
            datagramSocket.receive(datagramPacket);
            long fileSize = Long.parseLong(new String(buff, 0, datagramPacket.getLength()));
            while (fileSize > 0) {
                datagramSocket.receive(datagramPacket);
                length = datagramPacket.getLength();
                fileOutputStream.write(buff, 0, length);
                fileSize -= length;
            }
            datagramSocket.receive(datagramPacket);
            System.out.println(new String(buff, 0, datagramPacket.getLength()));
        }
    }
    
    @Override
    public void run() {
        try {
                accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
}
/**
 * @author aachen0
 * @date 2018/4/16 21:01
 * IDE:IntelliJ IDEA
 */
class Upload {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();
        File fileUpload = new File("recieve.png");
        FileInputStream fileInputStream = new FileInputStream(fileUpload);
        byte[] buff = new byte[1024];
        int length = 0;
        DatagramPacket datagramPacket = new DatagramPacket(buff, 0, length, InetAddress.getByName("127.0.0.1"), 9999);
        send(fileUpload.getName().getBytes(), datagramPacket, datagramSocket);// 上传文件前先传输文件名
        send((fileUpload.length() + "").getBytes(),datagramPacket , datagramSocket);// 文件长度
        while (-1 != (length = fileInputStream.read(buff))) {
            send(buff,datagramPacket,datagramSocket);
        }
        send("上传完毕!".getBytes(), datagramPacket, datagramSocket);
        
    }
    
    public static void send(byte[] info, DatagramPacket datagramPacket, DatagramSocket datagramSocket) throws IOException {
        datagramPacket.setData(info);
        datagramSocket.send(datagramPacket);
    }
}

你可能感兴趣的:(Java基础)