1.私聊形似
发送放:
InetAddress address = InetAddress.getByName(ad);//ad为String,接收方IP地址
byte[] message = msg.getBytes();//将发送形象转换为Byte类型
DatagramPacket packet = new DatagramPacket(message, message.length,address,9999);//实例化数据包
DatagramSocket socket = new DatagramSocket();//实例化套接字
socket.send(packet);//发送数据包
接收放:
byte[] buffer = new buffer[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);//接收数据包
DatagramSocket socket = new DatagramSocket(9999);//端口与发送方一致
socket.receive(packet);
String s = new String(packet.getData(), 0, packet.getLength());//转为String类型
2.群聊形式:
发送方:
InetAddress group = InetAddress.getByName("239.255.8.0");//创建群聊IP
byte[] message = msg.getBytes();//将发送形象转换为Byte类型
DatagramPacket packet = new DatagramPacket(date, date.length, group, port);//实例化数据包
MulticastSocket socket = new MulticastSocket(port);//实例化组播套接字
socket.setTimeToLive(1);//指定发送范围是本地网络
socket.joinGroup(group);//加入广播组
socket.send(packet);//发送数据
接收方:
InetAddress group = InetAddress.getByName("239.255.8.0");//实例化
byte[] buffer = new byte[8192];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
MulticastSocket socket = new MulticastSocket(port);//实例化组播套接字
socket.joinGroup(group);//加入广播组
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());