Java中利用DatagramPacket与DatagramSocket进行通讯的示例

对以下demo进行了扩展,增了消息循环和等待。

Java中的DatagramPacket与DatagramSocket的初步


扩展的代码如下:

1.接收端工程代码:

由于接收端的控制台log会被发送端的log冲掉,所以把log写到文件中。

package com.ameyume.receiver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Receiver {
    private static final String LOG_FILE_NAME = "receiver.txt";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 先删除旧的log文件
        File f = new File(LOG_FILE_NAME);
        if (f.exists()) {
            f.delete();
        }

        System.out.println(getDateString() + " Receiver main BEGIN >>>>>>\n");
        LogToFile("Receiver main BEGIN >>>>>>\n");

        try {
            // 确定接受方的IP和端口号,IP地址为本地机器地址
            InetAddress ip = InetAddress.getLocalHost();
            int port = 12365;
            for(int i = 0; i < 5; i++) {
                // 创建接收方的套接字,并指定端口号和IP地址  
                DatagramSocket getSocket = new DatagramSocket(port, ip);

                // 确定数据报接受的数据的数组大小  
                byte[] buf = new byte[1024];

                // 创建接受类型的数据报,数据将存储在buf中  
                DatagramPacket getPacket = new DatagramPacket(buf, buf.length);

                // 通过套接字接收数据, 此方法是阻塞的,会一直等待消息
                System.out.println(getDateString() + " Receiver begin receive message ...");
                LogToFile("Receiver begin receive message ...");
                getSocket.receive(getPacket);
                System.out.println(getDateString() + " Receiver end receive message ...");
                LogToFile("Receiver end receive message ...");

                // 解析发送方传递的消息,并打印
                String getMes = new String(buf, 0, getPacket.getLength());
                System.out.println(getDateString() + " Receiver 对方发送的消息:" + getMes);
                LogToFile("Receiver 对方发送的消息:" + getMes);

                // 通过数据报得到发送方的IP和端口号,并打印  
                InetAddress sendIP = getPacket.getAddress();
                int sendPort = getPacket.getPort();  
                System.out.println(getDateString() + " Receiver 对方的IP地址是:" + sendIP.getHostAddress());
                LogToFile("Receiver 对方的IP地址是:" + sendIP.getHostAddress());
                System.out.println(getDateString() + " Receiver 对方的端口号是:" + sendPort);
                LogToFile("Receiver 对方的端口号是:" + sendPort + '\n');

                // 通过数据报得到发送方的套接字地址
                SocketAddress sendAddress = getPacket.getSocketAddress();

                // 确定要反馈发送方的消息内容,并转换为字节数组
                String feedback = "接收方说:我收到了消息【" + getMes + "】";
                byte[] backBuf = feedback.getBytes();
      
                // 创建发送类型的数据报
                DatagramPacket sendPacket = new DatagramPacket(backBuf, backBuf.length, sendAddress);

                // 通过套接字发送数据
                getSocket.send(sendPacket);
                // 关闭套接字
                getSocket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        System.out.println(getDateString() + " Receiver main END <<<<<<");
        LogToFile("Receiver main END <<<<<<");
    }

    public static String getDateString() {
        SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss.SSS"); // 设置日期格式
        return df.format(new Date()); // new Date()为获取当前系统时间
    }

    public static void LogToFile(String log) {
        File sdFile = new File(LOG_FILE_NAME);

        try {
            FileWriter fw = new FileWriter(sdFile, true);
            fw.write(getDateString() + " " + log + '\n');
            fw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

2.发送端工程代码:

package com.ameyume.sender;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sender {
    private static final String LOG_FILE_NAME = "sender.txt";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 先删除旧的log文件
        File f = new File(LOG_FILE_NAME);
        if (f.exists()) {
            f.delete();
        }
        
        System.out.println(getDateString() + " Sender main BEGIN >>>>>>\n");
        LogToFile("Sender main BEGIN >>>>>>\n");

        try {
            // 创建发送方的套接字,IP默认为本地,不指定端口号则系统随机设置一个可用的端口号
            DatagramSocket sendSocket = new DatagramSocket(/*12341*/);

            for (int i = 0; i < 5; i++) {
                // 确定要发送的内容
                String msg = "你好,接收方:" + i;
                // 由于数据报的数据是以字节数组的形式存储的,所以转为转换数据
                byte[] buffer = msg.getBytes();

                // 确定发送方的IP地址及端口号,地址为本地机器地址
                int port = 12365;
                InetAddress ip = InetAddress.getLocalHost();

                // 创建发送类型的数据库
                // 构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号
                DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, ip, port);

                // 通过套接字发送数据
                System.out.println(getDateString() + " Sender send packet ..");
                LogToFile("Sender send packet ..");
                sendSocket.send(sendPacket);

                // 确定接收反馈数据的缓冲存储器,即存储数据的字节数组
                byte[] getBuffer = new byte[1024];

                // 确定接收类型的数据报
                DatagramPacket getPacket = new DatagramPacket(getBuffer, getBuffer.length);

                // 通过套接字接收数据
                System.out.println(getDateString() + " Sender receive packet ...");
                LogToFile("Sender receive packet ...");
                sendSocket.receive(getPacket);

                // 解析反馈的消息,并输出
                String backMsg = new String(getBuffer, 0, getPacket.getLength());
                System.out.println(getDateString() + " Sender 接收方返回的消息:" + backMsg);
                LogToFile("Sender 接收方返回的消息:" + backMsg);

                System.out.println(getDateString() + " Sender waiting 5s ...\n");
                LogToFile("Sender waiting 5s ...\n");

                Thread.sleep(5000);
            }

            // 关闭套接字
            sendSocket.close();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(getDateString() + " Sender main END <<<<<<");
        LogToFile("Sender main END <<<<<<");
    }

    public static String getDateString() {
        SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss.SSS"); // 设置日期格式
        return df.format(new Date()); // new Date()为获取当前系统时间
    }

    public static void LogToFile(String log) {
        File file = new File(LOG_FILE_NAME);

        try {
            FileWriter fw = new FileWriter(file, true);
            fw.write(getDateString() + " " + log + '\n');
            fw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

3.先运行Receiver工程,正在阻塞等待接收发送方发送的消息,总共接收到了5个消息,每个消息间隔5秒钟

log输出如下:
05-19 12:10:13.115 Receiver main BEGIN >>>>>>

05-19 12:10:13.119 Receiver begin receive message ...
05-19 12:10:18.886 Receiver end receive message ...
05-19 12:10:18.886 Receiver 对方发送的消息:你好,接收方:0
05-19 12:10:18.887 Receiver 对方的IP地址是:127.0.0.1
05-19 12:10:18.887 Receiver 对方的端口号是:50312

05-19 12:10:18.887 Receiver begin receive message ...
05-19 12:10:23.890 Receiver end receive message ...
05-19 12:10:23.891 Receiver 对方发送的消息:你好,接收方:1
05-19 12:10:23.891 Receiver 对方的IP地址是:127.0.0.1
05-19 12:10:23.892 Receiver 对方的端口号是:50312

05-19 12:10:23.893 Receiver begin receive message ...
05-19 12:10:28.896 Receiver end receive message ...
05-19 12:10:28.897 Receiver 对方发送的消息:你好,接收方:2
05-19 12:10:28.898 Receiver 对方的IP地址是:127.0.0.1
05-19 12:10:28.902 Receiver 对方的端口号是:50312

05-19 12:10:28.903 Receiver begin receive message ...
05-19 12:10:33.906 Receiver end receive message ...
05-19 12:10:33.907 Receiver 对方发送的消息:你好,接收方:3
05-19 12:10:33.907 Receiver 对方的IP地址是:127.0.0.1
05-19 12:10:33.908 Receiver 对方的端口号是:50312

05-19 12:10:33.909 Receiver begin receive message ...
05-19 12:10:38.923 Receiver end receive message ...
05-19 12:10:38.924 Receiver 对方发送的消息:你好,接收方:4
05-19 12:10:38.925 Receiver 对方的IP地址是:127.0.0.1
05-19 12:10:38.925 Receiver 对方的端口号是:50312

05-19 12:10:38.926 Receiver main END <<<<<<

4. 再运行Sender工程,每间隔5秒钟发送一个消息给发送方,共发送了5个消息
接收方都收到了,并有返回消息给发送方
log输出如下:
05-19 12:10:18.881 Sender main BEGIN >>>>>>

05-19 12:10:18.885 Sender send packet ..
05-19 12:10:18.886 Sender receive packet ...
05-19 12:10:18.887 Sender 接收方返回的消息:接收方说:我收到了消息【你好,接收方:0】
05-19 12:10:18.888 Sender waiting 5s ...

05-19 12:10:23.889 Sender send packet ..
05-19 12:10:23.890 Sender receive packet ...
05-19 12:10:23.893 Sender 接收方返回的消息:接收方说:我收到了消息【你好,接收方:1】
05-19 12:10:23.894 Sender waiting 5s ...

05-19 12:10:28.895 Sender send packet ..
05-19 12:10:28.896 Sender receive packet ...
05-19 12:10:28.903 Sender 接收方返回的消息:接收方说:我收到了消息【你好,接收方:2】
05-19 12:10:28.904 Sender waiting 5s ...

05-19 12:10:33.905 Sender send packet ..
05-19 12:10:33.906 Sender receive packet ...
05-19 12:10:33.921 Sender 接收方返回的消息:接收方说:我收到了消息【你好,接收方:3】
05-19 12:10:33.921 Sender waiting 5s ...

05-19 12:10:38.922 Sender send packet ..
05-19 12:10:38.923 Sender receive packet ...
05-19 12:10:38.926 Sender 接收方返回的消息:接收方说:我收到了消息【你好,接收方:4】
05-19 12:10:38.927 Sender waiting 5s ...

05-19 12:10:43.928 Sender main END <<<<<<

发布了270 篇原创文章 · 获赞 273 · 访问量 377万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览