UDP 多播

阅读更多

 

package tmp.net.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.atomic.AtomicBoolean;

public class Multicast {

	private MulticastSocket socket;
	private InetAddress group;
	private int port;
	private MulticastReceiver multicastReceiver;
	
	public Multicast(String ip, int port) throws IOException{
		this.port = port;
		group = InetAddress.getByName(ip);
		socket = new MulticastSocket(port);
		socket.joinGroup(group);
	}
	
	public void startReceive(DatagramPacketReceiver datagramPacketReceiver){
		if(multicastReceiver == null){
			multicastReceiver = new MulticastReceiver(socket, datagramPacketReceiver);
			multicastReceiver.start();
		}
	}
	
	public void send(DatagramPacket datagramPacket) throws IOException{
		datagramPacket.setAddress(group);
		datagramPacket.setPort(port);
		socket.send(datagramPacket);
	}
	
	public void shutdown() {
		if(socket != null){
			try {
				socket.leaveGroup(group);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			if(multicastReceiver != null){
				multicastReceiver.shutdown();
			}
			
			socket.close();
		}
	}
}

class MulticastReceiver extends Thread{
	
	private MulticastSocket socket;
	private DatagramPacketReceiver datagramPacketReceiver;
	private AtomicBoolean stopping = new AtomicBoolean(false);
	
	public MulticastReceiver(MulticastSocket socket, DatagramPacketReceiver datagramPacketReceiver) {
		super("MulticastReceiver");
		this.socket = socket;
		this.datagramPacketReceiver = datagramPacketReceiver;
	}
	
	public void run(){
		while(!stopping.get()){
			try {
				DatagramPacket datagramPacket = datagramPacketReceiver.newDatagramPacket(); 
				socket.receive(datagramPacket);  
				datagramPacketReceiver.onReceive(datagramPacket);
			} catch (Exception e) {
				e.printStackTrace();
			}   
        } 
	}
	
	public void shutdown(){
		stopping.set(true);
		
		interrupt();
	}
	
}

 

 

package tmp.net.socket.udp;

import java.net.DatagramPacket;

public interface DatagramPacketReceiver {

	public DatagramPacket newDatagramPacket();
	
	public void onReceive(DatagramPacket datagramPacket)throws Exception;
	
}

 

 

package tmp.net.socket.udp;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.nio.ByteBuffer;

public class PacketBuffer {

	private ByteBuffer buf;
	
	public PacketBuffer(int size){
		buf = ByteBuffer.allocate(size);
	}
	
	public PacketBuffer(byte[] data){
		buf = ByteBuffer.wrap(data);
	}
	
	public int readInt(){
		return buf.getInt();
	}
	
	public void writeInt(int data){
		buf.putInt(data);
	}
	
	public long readLong(){
		return buf.getLong();
	}
	
	public void writeLong(long data){
		buf.putLong(data);
	}
	
	public String readString(){
		int len = buf.getInt();
		switch (len) {
		case -1:
			return null;
		case 0:
			return "";
		default:
			byte[] data = new byte[len];
			buf.get(data);
			try {
				return new String(data, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public void writeString(String str){
		if(str == null){
			buf.putInt(-1);
			return ;
		}
		if(str.equals("")){
			buf.putInt(0);
			return ;
		}
		try {
			byte[] data = str.getBytes("UTF-8");
			buf.putInt(data.length);
			buf.put(data);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public DatagramPacket build(){
		for(int i = buf.position(); i 
  

 

测试服务端:

 

Multicast multicast = new Multicast("228.5.6.7", 6789);
		
		multicast.startReceive(new DatagramPacketReceiver(){

			@Override
			public DatagramPacket newDatagramPacket() {
				return new DatagramPacket(new byte[100], 100);
			}

			@Override
			public void onReceive(DatagramPacket datagramPacket) throws Exception {
				PacketBuffer packetBuilder = new PacketBuffer(datagramPacket.getData());
				System.out.println(packetBuilder.readString());
			}
			
		});

 

测试客户端:

 

Multicast multicast = new Multicast("228.5.6.7", 6789);
		
		multicast.startReceive(new DatagramPacketReceiver(){

			@Override
			public DatagramPacket newDatagramPacket() {
				return new DatagramPacket(new byte[100], 100);
			}

			@Override
			public void onReceive(DatagramPacket datagramPacket) throws Exception {
				PacketBuffer packetBuilder = new PacketBuffer(datagramPacket.getData());
				System.out.println(packetBuilder.readString());
			}
			
		});
		
		PacketBuffer packetBuilder = new PacketBuffer(100);
		packetBuilder.writeString("222");
		multicast.send(packetBuilder.build());

 

 

你可能感兴趣的:(UDP 多播)