Java UDP数据报发送与接收 学习

java中DatagramPacket表示存放数据的数据报,DatagramSocket表示接受或发送数据报的套接字。

这两个类所有构成的网络链接是基于UDP协议的。

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Sender {
    public static void main(String[] args) {
        try {
            // 创建发送方的套接字,IP默认为本地,端口号随机
            DatagramSocket sendSocket = new DatagramSocket();

            // 确定要发送的消息:
            String mes = "你好!接收方!";

            // 由于数据报的数据是以字符数组传的形式存储的,所以传转数据
            byte[] buf = mes.getBytes();

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

            // 创建发送类型的数据报:
            DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, ip, port);

            // 通过套接字发送数据:
            sendSocket.send(sendPacket);

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

            // 创建接受类型的数据报
            DatagramPacket getPacket = new DatagramPacket(getBuf, getBuf.length);

            // 通过套接字接受数据
            sendSocket.receive(getPacket);

            // 解析反馈的消息,并打印
            String backMes = new String(getBuf, 0, getPacket.getLength());
            System.out.println("接受方返回的消息:" + backMes);

            // 关闭套接字
            sendSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}



import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;

public class Receive {
    public static void main(String[] args) {
        try {
            // 确定接受方的IP和端口号,IP地址为本地机器地址
            InetAddress ip = InetAddress.getLocalHost();
            int port = 8888;

            // 创建接收方的套接字,并制定端口号和IP地址
            DatagramSocket getSocket = new DatagramSocket(port, ip);

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

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

            // 通过套接字接收数据
            getSocket.receive(getPacket);

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

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

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

            // 确定要反馈发送方的消息内容,并转换为字节数组
            String feedback = "接收方说:我收到了!";
            byte[] backBuf = feedback.getBytes();

            // 创建发送类型的数据报
            DatagramPacket sendPacket = new DatagramPacket(backBuf,
                    backBuf.length, sendAddress);

            // 通过套接字发送数据
            getSocket.send(sendPacket);

            // 关闭套接字
            getSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class WC7 extends Frame implements ActionListener,Runnable
{
    DatagramSocket D;
    byte dataBuf[] = new byte[512];
    InetAddress A;
    DatagramPacket Pac = new DatagramPacket(dataBuf,dataBuf.length);
    TextArea T1 = new TextArea();
    TextField T2 = new TextField(23);
    public WC7()
        {
            add(T1,"Center");
            Panel P = new Panel();
            P.add(new Label ("发送的信息"));
            P.add(T2);
            T2.addActionListener(this);
            add(P,"South");
            setSize(350,200);
            setVisible(true);
            setTitle("WC7");
            addWindowListener (new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
            (new Thread (this)).start();
        }
    public void actionPerformed(ActionEvent e1){
        try {
            String str = T2.getText();
            byte[] buf = str.getBytes();
            DatagramSocket D = new DatagramSocket();
            InetAddress A = InetAddress.getLocalHost();
            DatagramPacket P1 = new DatagramPacket (buf,buf.length,A,8002);
            D.send(P1);
            T2.setText("");
        }
        catch(Exception e2){
        }
    }
    public void run()
    {
        try {
            DatagramSocket D = new DatagramSocket(8001);
            while(true)
            {
                D.receive(Pac);
                String str = new String(Pac.getData(),0,Pac.getLength());
                T1.append(Pac.getAddress()+" WC7说 "+str+"\n");
                 
            }
        }
        catch(Exception e3){
        }
         
    }
    public static void main(String args[]){
        new WC7();
 
    }
     
 
}

 

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class WS7 extends Frame implements ActionListener,Runnable
{
    DatagramSocket D;
    byte dataBuf[] = new byte[512];
    InetAddress A;
    DatagramPacket Pac = new DatagramPacket(dataBuf,dataBuf.length);
    TextArea T1 = new TextArea();
    TextField T2 = new TextField(23);
    public WS7()
        {
            add(T1,"Center");
            Panel P = new Panel();
            P.add(new Label ("发送的信息"));
            P.add(T2);
            T2.addActionListener(this);
            add(P,"South");
            setSize(350,200);
            setVisible(true);
            setTitle("WS7");
            addWindowListener (new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
            (new Thread (this)).start();
             
             
        }
    public void actionPerformed(ActionEvent e1){
        try {
            String str = T2.getText();
            byte[] buf = str.getBytes();
            DatagramSocket D = new DatagramSocket();
            InetAddress A = InetAddress.getLocalHost();
            DatagramPacket P1 = new DatagramPacket (buf,buf.length,A,8001);
            D.send(P1);
            T2.setText("");
        }
        catch(Exception e2){
        }
    }
    public void run()
    {
        try {
            DatagramSocket D = new DatagramSocket(8002);
            while(true)
            {
                D.receive(Pac);
                String str = new String(Pac.getData(),0,Pac.getLength());
                T1.append(Pac.getAddress()+" WS7说 "+str+"\n");
                 
            }
        }
        catch(Exception e3){
        }
         
    }
    public static void main(String args[]){
        new WS7();
    }
     
     
     
     
}

 

posted @ 2014-07-28 15:12  胖小白  阅读(1307)  评论(0编辑  收藏  举报