简体   繁体   English

使用UDP从C#组播到android

[英]multicasting from c# to android using UDP

I have developed UDP multicast server in c# and UDP multicast reciever in Android,but iam not able to recieve data from server to client(Android).Is it because of the port numbers i have used in code ? 我已经在c#中开发了UDP多点传送服务器,在Android中开发了UDP多点传送接收器,但是我无法从服务器到客户端(Android)接收数据。是因为我在代码中使用了端口号吗? Your help is greatly appretiated and will save me nights. 非常感谢您的帮助,这将为我节省很多时间。

***Server code ***服务器代码

namespace Server
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        UdpClient udpclient = new UdpClient();
        IPAddress multicastaddress = IPAddress.Parse("233.45.17.10");
        udpclient.JoinMulticastGroup(multicastaddress);
            IPEndPoint remoteep = new IPEndPoint(multicastaddress, 10000);
            Byte[] buffer = null;
            for (int i=1;i<30;i++)
            {
                buffer = Encoding.Unicode.GetBytes(i.ToString());
                int flag = udpclient.Send(buffer, buffer.Length, remoteep);
            }
            MessageBox.Show("Data Sent TO " + ip.Text + "On Port " + port.Text);
            status.Text = "Connected";
        }
        private void disconnect_Click(object sender, EventArgs e)
        {
        this.Close();
        }
    }
}***

Client code(Android): 客户端代码(Android):

public class TestMulticast extends Activity
    {
        static boolean done = false;
        EditText et;
        TextView tv;
Button b;
MulticastSocket socket;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    b=(Button)findViewById(R.id.b);
    et=(EditText)findViewById(R.id.et);
    tv =(TextView)findViewById(R.id.tv);

    b.setOnClickListener(new Button.OnClickListener()
    {
        public void onClick(View v) 
        {
           try 
           {
              String msg = et.getText().toString();
              socket.send(new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, InetAddress.getByName("192.168.1.6"), 10000));
              Toast.makeText(getApplicationContext(), "sent", 100).show();
           }
           catch (Exception e) 
           {
               e.printStackTrace();
               Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
           }
        }
});
if (!done) 
{
    try 
    {
        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiinfo = wifiManager.getConnectionInfo();
        int intaddr = wifiinfo.getIpAddress();
        if (intaddr == 0)
        {
            tv.setText("Unable to get WIFI IP address");
        }
        else 
        {
            byte[] byteaddr = null;
            byteaddr = new byte[] {
                            (byte)(intaddr & 0xff), 
                    (byte)(intaddr >> 8 & 0xff),
                    (byte)(intaddr >> 16 & 0xff),
                    (byte)(intaddr >> 24 & 0xff)
                };
       String machineName = "androidtestdevice";
       InetAddress addr = InetAddress.getByAddress(machineName, byteaddr);
       tv.append("Using address: " + addr + "\n");
       Toast.makeText(getApplicationContext(), "using address"+addr, 50).show();
      // create socket
      socket = new MulticastSocket(11111);
      // set network interface
      NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
      Toast.makeText(getApplicationContext(), "First address on interface is: " + getAddressFor(iface), 50).show();
      tv.append("First address on interface is: " + getAddressFor(iface) + "\n");
     // The following line throws an exception in Android (Address is not available)
     // If it's not called, the socket can receives packets
     // Equivalent code in seems to C work.
     //socket.setNetworkInterface(iface);
     // join group
     socket.joinGroup(InetAddress.getByName("233.45.17.10"));
     tv.append("It worked\n");
    // start receiving
    new DatagramListener(socket, tv).start();

  }
  }
 catch (Exception e) {
 tv.append(e.toString() + "\n");
 e.printStackTrace();
 }
 }
 }

class DatagramListener extends Thread {
    private DatagramSocket socket;
    private TextView tv;
    DatagramListener(DatagramSocket s, TextView tv) {
    socket = s;
    this.tv = tv;
    }
    public void run() {
    byte[] buf = new byte[1000];
    try {
    while (true) {
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    socket.receive(recv);

    System.out.println("received: " + new String(recv.getData(), recv.getOffset(), recv.getLength()));


    runOnUiThread(new MyRunnable(new String(recv.getData(), recv.getOffset(), recv.getLength()), tv));
    Toast.makeText(getApplicationContext(), "Now showing data", Toast.LENGTH_SHORT).show();
    }
    }
    catch (Exception e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), "received: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    }
}
static private class MyRunnable implements Runnable {
    private TextView tv;
    private String text;
    public MyRunnable(String text, TextView tv) {
        this.tv = tv;
        this.text = text;
    }
    public void run() {
        tv.append(text + "\n");
    }
}
public static InetAddress getAddressFor(NetworkInterface iface) {
    Enumeration<InetAddress> theAddresses = iface.getInetAddresses();
    boolean found = false;
    InetAddress firstAddress = null;
    while ((theAddresses.hasMoreElements()) && (found != true)) {
        InetAddress theAddress = theAddresses.nextElement();
        if (theAddress instanceof Inet4Address) {
            firstAddress = theAddress;
            found = true;
        }
    }
    return firstAddress;
}

} }

Multicast packets are filtered in many android devices depending on vendor (some do others don't htc would filter it most likely), presumably to save battery. 多播数据包会根据供应商在许多android设备中进行过滤(有些人不会htc最有可能对其进行过滤),以节省电池。 it is not blocked in android as such but the vendors. 它没有像这样在android中被阻止,但在供应商中被阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM