UDP实现消息循环发送

UDP实现消息循环发送

  • 发送方
package com.caster.IP.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(8888);


           //准备数据 控制台读取 System.in
           BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
           while (true){
               String data = reader.readLine();
               byte[] datas = data.getBytes();
               DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
               socket.send(packet);
               if (data.equals("bye")){
                   break;
               }
           }
           socket.close();
    }
}
  • 接收方
package com.caster.IP.chat;

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

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(6666);


        while (true){
            //准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            socket.receive(packet);
            //断开连接
            byte[] data = packet.getData();
            String reveiveData = new String(data, 0, data.length);
            System.out.println(reveiveData);
            if (reveiveData.equals("bye")){
                break;
            }

        }
        socket.close();


    }
}
上一篇:java实现UDP聊天---转载


下一篇:交叉验证(Cross Validation)简介