gpt4 book ai didi

java - Java-Android 上的 MulticastSocket 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:53:02 26 4
gpt4 key购买 nike

我开始使用 MulticastSocket 编写代码,尝试制作一个简单的应用程序,使用客户端和服务器来发送消息。

我为服务器准备的代码:

    import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;


public class Servidor {
private static MulticastSocket ms;
public static void main(String[] args) throws IOException{

InetAddress sessAddr = InetAddress.getByName("224.2.76.24");
try{
sessAddr = InetAddress.getByName("224.2.76.24");
ms = new MulticastSocket(5500);
ms.joinGroup(sessAddr);

while (true)
{
byte[] mensaje = new byte[1024];
mensaje = "aa".getBytes();
DatagramPacket dp = new DatagramPacket(mensaje, mensaje.length,sessAddr,5500);
ms.send(dp);
}
}
catch (SocketException se) {
System.err.println(se);
}

ms.leaveGroup(sessAddr);

}

}

这在客户端:

    package com.example;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class ClienteMultiCast extends Activity {
/** Called when the activity is first created. */


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView Mensaje;
Mensaje =(TextView)findViewById(R.id.Mensaje);


InetAddress ia = null;
byte[] buffer = new byte[65535];
MulticastSocket ms = null;
int port = 5500;
try {
ia = InetAddress.getByName("224.2.76.24");
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,ia,port);
ms = new MulticastSocket(port);
ms.joinGroup(ia);
while (true) {
ms.receive(dp);
String s = new String(dp.getData(),0,dp.getLength());
Mensaje.setText(s);
}

} catch (UnknownHostException e) {Mensaje.setText(e.getMessage());} catch (IOException e) {Mensaje.setText(e.getMessage()); }

try {
ms.leaveGroup(ia);
} catch (IOException e) {
Mensaje.setText(e.getMessage());
}
}
}

问题是,当我启动两者时,没有任何反应。客户端没有收到任何消息。

知道哪里出了问题吗?

最佳答案

迭戈,

默认情况下,Android WiFi 堆栈会过滤掉多播数据包。看看http://developer.android.com/reference/android/net/wifi/WifiManager.MulticastLock.html .

你需要一些类似的东西:

  public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

/* Turn off multicast filter */
MulticastLock mcastLock = new MulticastLock();
mcastLock.acquire();

/* Process Multicast Packets */

}

关于java - Java-Android 上的 MulticastSocket 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4589946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com