您的位置:首页 > 编程语言 > Java开发

java基于socket的组播协议实现代码(局域网聊天室)

2016-04-13 08:49 686 查看
背景:N台设备需要在同组局域网内搜索到带有某个特征的设备,该设备接收到消息以后同样以组播的方式返回信息,两两交换ip地址以后实现一对一的信息交互。

上代码:

package com.sdzn.web.service.socket;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Date;

/**
* 类MulticastProtocol.java的实现描述:组播协议socket实现,有服务端和客户端
*
* @author : Ricky
* @createTime : Apr 13, 2016 8:46:42 AM
*/
public class MulticastProtocol {

/**
* multicastClient方法描述:组播客户端实现,用于向加入的组播其它用户发送组播消息
*
* @author : Ricky
* @createTime : Apr 13, 2016 8:44:58 AM
* @throws Exception
*/
public static void multicastClient() throws Exception {
InetAddress group = InetAddress.getByName("239.0.0.9");// 组播地址
int port = 1234;// 组播端口
MulticastSocket mss = null;// 创建组播套接字
try {
mss = new MulticastSocket(port);
mss.joinGroup(group);
System.out.println("发送数据包启动!(启动时间" + new Date() + ")");

String message = "Box_ " + new Date();
byte[] buffer = message.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
group, port);
mss.send(dp);
System.out.println("发送数据包给 " + group + ":" + port);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (mss != null) {
mss.leaveGroup(group);
mss.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

/**
* multicastServer方法描述:组播服务端实现,用于监听组播中的消息,在接收到消息以后再向组播中的其它成员反馈消息
*
* @author : Ricky
* @createTime : Apr 13, 2016 8:45:25 AM
* @throws Exception
*/
public static void multicastServer() throws Exception {
InetAddress group = InetAddress.getByName("239.0.0.9");// 组播地址
int port = 1234;// 组播端口
MulticastSocket msr = null;// 创建组播套接字
try {
msr = new MulticastSocket(port);
msr.joinGroup(group);// 加入连接
byte[] buffer = new byte[8192];
System.out.println("接收数据包启动!(启动时间: " + new Date() + ")");
while (true) {
// 建立一个指定缓冲区大小的数据包
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
msr.receive(dp);
String s = new String(dp.getData(), 0, dp.getLength());
// 解码组播数据包
System.out.println("接收到的组播数据包是:" + s);
multicastClient();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (msr != null) {
try {
msr.leaveGroup(group);
msr.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}

/**
* main方法描述:主函数测试
*
* @author : Ricky
* @createTime : Apr 13, 2016 8:46:26 AM
* @param args
*/
public static void main(String[] args) {
try {
multicastServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息