Java网络编程03:UDP

Java网络编程03:UDP

发短信:不用连接,需要知道对方的地址!

UDP消息发送

发送端

//不需要连接服务器
public class UdpClientDemo01 {
     
    public static void main(String[] args) throws Exception {
     
        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //2.建个包
        String msg = "你好,服务器";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;

        //数据,数据的长度起始,发送给谁
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);

        //3发送包
        socket .send(packet);
        //4.关闭流
        socket.close();

    }
}

接收端

//还是要等待客户端的连接!
public class UdpServerDemo01 {
     

    public static void main(String[] args) throws Exception {
     

        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet); //阻塞接收

        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //关闭连接
        socket.close();

    }

}

循环发送消息

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();

    }

}
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);//阻塞式接收包裹

            //断开连接 bye
            byte[] data = packet.getData();
            String receiveData = new String(data,0,data.length);

            System.out.println(receiveData);

            if (receiveData.equals("bye")){
     
                break;
            }

        }

        socket.close();

    }

}

聊天室案例:

public class TalkSend implements Runnable {
     

    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort,String toIP,int toPort){
     
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
     
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e){
     

        }

    }

    @Override
    public void run() {
     

        while (true){
     
            try {
     
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));

                socket.send(packet);
                if (data.equals("bye")){
     
                    break;
                }
            } catch (Exception e) {
     
                e.printStackTrace();
            }
        }

        socket.close();

    }
}
public class TalkReceive implements Runnable {
     

    DatagramSocket socket = null;
    private int port;
    private String msgFrom;


    public TalkReceive(int port,String msgFrom){
     
        this.port = port;
        this.msgFrom = msgFrom;
        try {
     
            socket = new DatagramSocket(port);
        }catch (Exception e){
     

        }

    }

    @Override
    public void run() {
     

        while (true){
     

            try {
     
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet);//阻塞式接收包裹

                //断开连接  bye
                byte[] data = packet.getData();
                String receiveData = new String(data,0,data.length);

                System.out.println(msgFrom+":"+receiveData);

                if (receiveData.equals("bye")){
     
                    break;
                }

            }catch (Exception e){
     
                e.printStackTrace();
            }

        }
        socket.close();
    }
}
public class TalkStudent {
     

    public static void main(String[] args) {
     

        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();

    }

}
public class TalkTeacher {
     

    public static void main(String[] args) {
     
        //开启两个线程
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }

}

URL

public class URLDemo01 {
     

    public static void main(String[] args) throws MalformedURLException {
     

        URL url = new URL("http://localhost:8080/helloword/index.jsp?username=zhangsan&password=123");
        System.out.println(url.getProtocol());//协议
        System.out.println(url.getHost());//主机ip
        System.out.println(url.getPort());//端口
        System.out.println(url.getPath());//文件
        System.out.println(url.getFile());//全路径
        System.out.println(url.getQuery());//参数

    }

}

文件下载

public class UrlDown {
     

    public static void main(String[] args) throws Exception {
     

        //1.下载地址
        URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595394077&di=d5136d84fb7c4265752c19242428233b&imgtype=jpg&er=1&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201111%2F21%2F205700txzuacubbcy91u99.jpg");

        //2.连接到这个资源  HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("9.jpg");

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
     
            fos.write(buffer,0,len);//写出这个数据
        }

        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }

}

你可能感兴趣的:(Java网络编程,Java基础,网络,java,udp)