android socket组播,Android无法接收组播数据包

我正在玩多播套接字.我写了一个服务器,它向

Android客户端发送消息.直到客户端应该只记录收到的消息.

我注意到我的设备上没有收到任何多播数据包.

这是服务器的代码(在PC上运行):

public class MulticastServer{

private int port;

private boolean running = false;

private MulticastSocket serverSocket;

private InetAddress group;

private String multicastAddress = "230.192.0.11";

public MulticastServer(int port) {

super();

this.port = port;

init();

}

public MusicStreamerServer() {

this(5500);

}

private void init() {

try {

group = InetAddress.getByName(multicastAddress);

serverSocket = new MulticastSocket(port);

serverSocket.joinGroup(group);

} catch (IOException e) {

e.printStackTrace();

}

}

public void start() throws IOException {

System.out.println("server started");

if (running)

return;

running = true;

new Thread(new Runnable() {

@Override

public void run() {

byte[] buf = new byte[1024];

DatagramPacket packet = new DatagramPacket(buf, buf.length,

group, port);

String msg = "msg";

while (running) {

packet.setData(msg.getBytes(), 0, msg.length());

try {

serverSocket.send(packet);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}).start();

}

public void stop() throws IOException {

running = false;

} }

这是android客户端的代码:

public class MainActivity extends Activity {

private MulticastSocket socket;

private InetAddress group;

private String multicastAddress = "230.192.0.11";

private int port = 5500;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

init();

}

private void init() {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

.permitAll().build();

StrictMode.setThreadPolicy(policy);

try {

group = InetAddress.getByName(multicastAddress);

socket = new MulticastSocket(port);

socket.joinGroup(group);

socket.setBroadcast(true);

} catch (IOException e) {

e.printStackTrace();

Log.wtf("init", e.getMessage());

}

new Thread(new Runnable() {

@Override

public void run() {

WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);

WifiManager.MulticastLock multicastLock = wm

.createMulticastLock("mylock");

multicastLock.acquire();

byte[] buf = new byte[1024];

while (true) {

try {

socket.receive(packet);

Log.d("receiver","received = " + (new String(packet.getData())));

} catch (IOException e) {

e.printStackTrace();

}

}

}

}).start();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

return true;

}}

我用2种不同的设备测试了代码. Nexus4和Nexus7(2013)都运行最新的Android.

有人能帮助我吗?

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值