Java教程

Udp通信

本文主要是介绍Udp通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

多发多收

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

这篇关于Udp通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!