多发多收
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);
}
}
}
组播
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);
}
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282296.html