工具1:Eclipse
工具2:IntelliJ IDEA
Java工程的目录结构(基于IntelliJ IDEA)
例1.1:接收方,因为接收到的数据是字节流,为了方便,这里是基于Apache commons IO,将字节流读到一个文本文档中。
1 import org.apache.commons.io.FileUtils;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.net.DatagramPacket;
6 import java.net.DatagramSocket;
7
8 public class Receiver {
9
10 public static void main(String[] args) throws IOException {
11 DatagramSocket you = new DatagramSocket(6666);
12 byte[] buffer = new byte[1024 * 8];
13 DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
14 you.receive(datagramPacket);
15 FileUtils.writeByteArrayToFile(new File("postcard.txt"), datagramPacket.getData(), 0, datagramPacket.getLength());
16 System.out.println(FileUtils.readFileToString(new File("postcard.txt"), "UTF-8"));
17 you.close();
18 }
19 }
Java工程的目录结构(基于Eclipse)
例1.2:发送方,发送一个名为postcard的文本文档。因为传输的是字节流,所以需要将文本文档转换为字节数组,为了方便,这里是基于Apache commons IO,将文本文档的内容读到一个字节数组中。
1 import java.io.File;
2 import java.io.IOException;
3 import java.net.DatagramPacket;
4 import java.net.DatagramSocket;
5 import java.net.InetSocketAddress;
6
7 import org.apache.commons.io.FileUtils;
8
9 public class Sender {
10
11 public static void main(String[] args) throws IOException {
12 DatagramSocket i = new DatagramSocket(8888);
13 byte[] buffer = FileUtils.readFileToByteArray(new File("postcard.txt"));
14 DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress("localhost", 6666));
15 i.send(datagramPacket);
16 i.close();
17
18 System.out.println("I sent you a postcard.");
19 }
20 }
先运行接收方,再运行发送方。如果都能顺利运行,接收方的控制台输出接收到的内容。例如我的是:
I miss you.