首页 > 编程学习 > Udp通信

Udp通信

发布时间:2022/8/26 4:52:42

多发多收

client

package ClientDemo;

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

public class client {
    public static void main(String[] args) throws Exception {
        DatagramSocket client = new DatagramSocket();
        Scanner sc = new Scanner(System.in);
        String msg = "";
        while(true) {
            System.out.println("您说");
            msg = sc.nextLine();
            if(msg.equals("exit")) {
                System.out.println("断开连接");
                client.close();
                break;
            }
            byte[] buffer = msg.getBytes();
            DatagramPacket packet= new DatagramPacket(buffer,buffer.length,InetAddress.getLocalHost(),8888);
            client.send(packet);
        }
    }
}

server

package ClientDemo;

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

public class Server {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        byte[] bytes = new byte[1024*60];
        DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
        while(true) {
            socket.receive(packet);
            String res = new String(bytes);
            System.out.println(res);
        }

    }
}

image

组播

server

package ClientDemo;

import java.net.*;

public class Server {
    public static void main(String[] args) throws Exception {
        MulticastSocket socket = new MulticastSocket(9999);
//        socket.joinGroup(InetAddress.getByName("224.0.1.1"));
        socket.joinGroup(new InetSocketAddress(InetAddress.getByName("224.0.1.1"),9999),NetworkInterface.getByInetAddress(InetAddress.getLocalHost()));
        byte[] bytes = new byte[1024*60];
        DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
        while(true) {
            socket.receive(packet);
            String res = new String(bytes);
            System.out.println(res);
        }

    }
}

client

package ClientDemo;

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

public class client {
    public static void main(String[] args) throws Exception {
        DatagramSocket client = new DatagramSocket();
        Scanner sc = new Scanner(System.in);
        String msg = "";
        while(true) {
            System.out.println("您说");
            msg = sc.nextLine();
            if(msg.equals("exit")) {
                System.out.println("断开连接");
                client.close();
                break;
            }
            byte[] buffer = msg.getBytes();
            DatagramPacket packet= new DatagramPacket(buffer,buffer.length,InetAddress.getByName("224.0.1.1"),9999);
            client.send(packet);
        }
    }
}

Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号