Udp发送消息---BufferedReader\

发送方

  • //不需要连接服务器
  • //1建立一个socket
  • //2建一个包
  • //3数据,数据的长度起始,要发给谁
  • //4发送包
  • //5关闭流
package Liu.UdpTalk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UdpClient {
    public static void main(String[] args) throws IOException {
        //创建一个数据插座
        DatagramSocket ds = new DatagramSocket(6666);
        while (true) {
            //准备数据:控制台读取:System.in
            BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
            String data = buffer.readLine();
            //将数据打包成数据包
            InetAddress IP = InetAddress.getByName("127.0.0.1");
            DatagramPacket dp = new DatagramPacket(data.getBytes(), 0, data.getBytes().length, IP, 9991);
            //发送数据
            ds.send(dp);
            if(data.equals("bye")){break;}
        }
        //关闭数据
        ds.close();
    }
}

接收方

  • //开放端口
  • //接收包裹
  • //关闭连接
package Liu.UdpTalk;

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


public class UdpSever extends Thread {
    public static void main(String[] args) throws IOException {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9991);
        while (true) {
            //准备接收包裹
            byte[] container = new byte[100];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);
            //断开连接 bye
            byte[] Data = packet.getData();
            int len=packet.getLength();
            String receiveData = new String(Data, 0, len);
            System.out.println(receiveData);
            if (receiveData.equals("bye")) {
                break;
            }
        }
        socket.close();
    }
}
posted @ 2022-03-18 15:01  小幼虫虫  阅读(2)  评论(0)    收藏  举报