网络通信--UDP

[TOC]
网络通信--UDP_第1张图片

UDP实现收发数据

接收数据

(1)使用DatagramSocket(int port )创建一个数据包套接字,绑定到指定端口
(2)使用DataPacket(byte[] buf,int length)创建字节数组来接收数据包
(3)使用DatagramSocket类的receive()方法发送数据包
public static void main(String[] args) {
    try {
    //接收数据时必须指定端口
        DatagramSocket socket=new DatagramSocket(8080);
        byte [] array=new byte[1024];
        DatagramPacket pack=new DatagramPacket(array, 1024);
        socket.receive(pack);
        //把接收到的数据存入数组
        byte [] data=pack.getData();
        //将数组转化成字符串打印输出
        System.out.println(new String(data));
        //System.out.println(new String(array,0,pack.getLength())); 用getLength()得到要接受或发送数据的长度
        //最后一定要将流关闭
        socket.close();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

发送数据

(1)使用DatagramSocket( )创建一个数据包套接字
(2)使用DataPacket(byte[] buf,int offset,int length,InetAddress address,port)创建要发送的数据包
(3)使用DatagramSocket类的send()方法发送数据包
public static void main(String[] args) {
        try {
        //发送时不用指定端口
            DatagramSocket  send=new DatagramSocket();
            String a="duyongkang";
            byte[]array=a.getBytes();
            //指定要发送到的主机,数据和端口号
            DatagramPacket pack=new DatagramPacket(array, array.length,InetAddress.getLocalHost(),8080);
            send.send(pack);//发送数据
            System.out.println("已经发送数据");
            send.close();//最后将流关闭
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

UDP相互交流

先运行接收,在运行发送

接收数据代码部分

//接收数据代码部分
public static void main(String[] args) {
    try {
        DatagramSocket socket=new DatagramSocket(8080);
        DatagramPacket pack=null;
        DatagramSocket  send=new DatagramSocket();
        Scanner input=new Scanner(System.in);
        DatagramPacket pac=null;
        while(true){
        byte [] array=new byte[1024];
        pack=new DatagramPacket(array, 1024);
        socket.receive(pack);
        byte [] data=pack.getData();
         //System.out.println(new String(array,0,pack.getLength())); 用getLength()得到要接受或发送数据的长度
        System.out.println(new String(data));
        String str=input.next();
        byte[]array1=str.getBytes();
        pac=new DatagramPacket(array1, array1.length,InetAddress.getByName("192.168.0.31"),8081);
    send.send(pac);
    System.out.println("已经发送数据");
        }
        //socket.close();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

发送数据代码部分

public static void main(String[] args) {
        try {
            DatagramSocket socket=new DatagramSocket(8081);
            DatagramPacket pack=null;
            DatagramSocket  send=new DatagramSocket();
            Scanner input=new Scanner(System.in);
            DatagramPacket pac=null;
            while(true){
                String str=input.next();
                byte[]array=str.getBytes();
                //用getByName得到ip地址
                pac=new DatagramPacket(array, array.length,InetAddress.getByName("192.168.0.31"),8080);
            send.send(pac);
            System.out.println("已经发送数据");
            byte [] array1=new byte[1024];
            pack=new DatagramPacket(array1, 1024);
            socket.receive(pack);
            byte [] data=pack.getData();
            System.out.println(new String(data));
            }
            //send.close();//最后将流关闭
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

在界面上聊天

//**********************************************
public class MyClientRead implements Runnable{
     private  MyClient client;
     public MyClientRead(MyClient client){
         this.client=client;
     }
    @Override
    public void run() {
        while(true){
            client.read();
        }


    }

}
//*******************************************
public class MyServerRead implements Runnable{
   private MyServer server;
   private Socket socket;
   public MyServerRead(MyServer server,Socket socket){
       this.server=server;
       this.socket=socket;
   }

    @Override
        public void run() {
        while(server.isRunning()){
            server.read(socket);
        }

        }
}
//*********************************************
public class MyClient extends JFrame {

    private JPanel contentPane;
    private JList list;
    private JTextArea textArea;
    private Socket socket;
    private DefaultListModel<String> modle;
    /** * Launch the application. */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyClient frame = new MyClient();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /** * Create the frame. */
    public MyClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("发送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton.setBounds(314, 201, 93, 51);
        contentPane.add(btnNewButton);

        textArea = new JTextArea();
        textArea.setBounds(41, 201, 240, 51);
        contentPane.add(textArea);

        list = new JList();
        list.setBounds(41, 25, 240, 157);
        modle=new DefaultListModel<>();
        list.setModel(modle);
        contentPane.add(list);

        JButton btnNewButton_1 = new JButton("连接服务器");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("连接服务器");
                    socket=new Socket("localhost", 8080);
                    System.out.println("连接服务器成功");
                    Thread t=new Thread(new MyClientRead(MyClient.this));
                    t.start();
                    } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton_1.setBounds(314, 47, 93, 42);
        contentPane.add(btnNewButton_1);
    }

    public void write(){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            String words=   textArea.getText();
            bw.write(words+"\n");
    modle.addElement(words);
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            modle.addElement(""+line);//让服务器说的话出现在客户端的JList list上
            System.out.println(line);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



}
//****************************************
public class MyServer extends JFrame {

    private JPanel contentPane;
    private ArrayList<Socket> sockets;
    private JTextArea textArea;
    private boolean isRunning = true;
    private JButton btnNewButton_1;
    private JList list;
    private DefaultListModel<String> modle;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    /** * Launch the application. */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyServer frame = new MyServer();//????????????????????????????????????
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /** * Create the frame. */
    public MyServer() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 481, 358);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        JButton btnNewButton1 = new JButton("开启服务器 ");

        btnNewButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                isRunning = true;
                //这个线程等待客户端链接服务器
                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            ServerSocket server = new ServerSocket(8080);
                            System.out.println("服务器启动");
                            sockets = new ArrayList<>();
                            while (isRunning) {
                                Socket socket = server.accept();//等待客户端连接进来
                                sockets.add(socket);
                                //下边这个线程专门用来等待socket发送过来的信息
                                //????????????????
                                Thread t = new Thread(new MyServerRead(MyServer.this,socket));
                                t.start();
                                System.out.println("有客户端连接");
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }


                    }
                }).start();
// ;
            }
        });

        btnNewButton1.setBounds(362, 36, 93, 45);
        contentPane.add(btnNewButton1);

        textArea = new JTextArea();
        textArea.setBounds(39, 250, 303, 45);
        contentPane.add(textArea);

        btnNewButton_1 = new JButton("发送给客户");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //modle是干啥的?????????????
                modle.addElement(textArea.getText());
                write();
            }
        });
        btnNewButton_1.setBounds(352, 250, 93, 45);
        contentPane.add(btnNewButton_1);

        modle = new DefaultListModel<>();
        list = new JList();
        list.setModel(modle);
        list.setBounds(39, 21, 303, 219);
        contentPane.add(list);

    }

    public void read(Socket socket) {
        if (socket.isConnected()) {
            try {
                InputStream is = socket.getInputStream();//只能读字节
                InputStreamReader isr = new InputStreamReader(is);//读字符
                BufferedReader br = new BufferedReader(isr);//将字符换成一行
                String line = br.readLine();
                //让客户端的话出现在服务器的JList list上
                modle.addElement(socket.getInetAddress().getHostName() + " " + line);
                System.out.println(line);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            sockets.remove(socket);
        }

    }
    /** * 这里是服务器发送消息 */

    public void write() {
        try {
            for (Socket socket : sockets) {
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                String words = textArea.getText();
                System.out.println("服务器发送消息");
                bw.write(words + "\n");
                bw.flush();

            }
            textArea.setText("");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }

你可能感兴趣的:(网络通信--UDP)