2013-11-28 89 views
0

我想創建一個非常簡單的android UDP uni cast服務器和一個C#UDP客戶端。我們可以在android上創建服務器嗎?如果是,那麼應該給C#客戶端連接到android服務器的IP地址是什麼? 指導簡單的單播android udp服務器用c#udp客戶端

編輯:我已經完成了我的Android單播UDP服務器和C#中的單播UDP客戶端。 服務器正在發送DatagramPackets並且客戶端正在成功接收。但相反的情況並未發生,並且沒有任何錯誤和例外。但我無法理解代碼中的問題。

Android的服務器:

public class MainActivity extends Activity { 

String myIP; 
final Integer myPort = 12345; 

String clientIP = "192.168.1.3"; 
Integer clientPort = 54321; 

byte[] inBuffer,outBuffer; 

Button send, set; 
EditText sendMsg, receiveMsg, cip, cp; 

DatagramSocket me; 

AsyncTask<Void, byte[], Void> asyncReceiver; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    send = (Button) findViewById(R.id.button1); 
    sendMsg = (EditText) findViewById(R.id.editText1); 
    receiveMsg = (EditText) findViewById(R.id.editText2); 

    set = (Button) findViewById(R.id.button2); 
    cip = (EditText) findViewById(R.id.editText3); 
    cp = (EditText) findViewById(R.id.editText4); 

    inBuffer = new byte[256]; 
    outBuffer = new byte[256]; 

    myIP = null; 
    myIP = GetCurrentIP(); 

    if (myIP == null) { 
     Msg("GetCurrentIP error."); 
    } else { 
     try { 
      setTitle(myIP+"|"+InetAddress.getLocalHost()); 
     } catch (UnknownHostException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     if (!Bind()) { 
      Msg("Bind() error."); 
     } else { 

      set.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        clientIP = cip.getText().toString(); 
        clientPort = Integer.parseInt(cp.getText().toString()); 
        Msg(clientIP+"|"+clientPort); 
       } 
      }); 

      send.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        outBuffer = sendMsg.getText().toString().getBytes(); 
        SendToClient(); 
       } 
      }); 

      //----------- 
      asyncReceiver = new AsyncTask<Void, byte[], Void>() { 

       @Override 
       protected void onProgressUpdate(byte[]... values) { 
        // TODO Auto-generated method stub 
        super.onProgressUpdate(values); 
        receiveMsg.append(new String(values[0])); 
       } 

       @Override 
       protected Void doInBackground(Void... params) { 
        // TODO Auto-generated method stub 
        try { 
         while(true){ 
          inBuffer = new byte[256]; 
          DatagramPacket pack = new DatagramPacket(inBuffer, inBuffer.length, InetAddress.getByName(clientIP), clientPort); 
          me.receive(pack); 
          publishProgress(inBuffer); 
          Thread.sleep(500); 
         } 
        } catch (Exception e) { 
         // TODO: handle exception 
         Msg(e.getMessage()); 
        } 
        return null; 
       } 
      }; 
      //----------- 
      asyncReceiver.execute(new Void[1]); 
      Msg("Receiving started."); 

     } 
    } 
} 



private void SendToClient(){ 
    try { 
     DatagramPacket pack = new DatagramPacket(outBuffer, outBuffer.length, InetAddress.getByName(clientIP), clientPort); 
     me.send(pack); 
     Msg("Sent successfully."); 
    } catch (Exception e) { 
     // TODO: handle exception 
     Msg(e.getMessage()); 
    } 
} 

private boolean Bind(){ 
    try { 
//   DatagramChannel channel = DatagramChannel.open(); 
//   me = channel.socket(); 
//   //me = new DatagramSocket(); 
//   SocketAddress localAddr = new InetSocketAddress(InetAddress.getByName(myIP), myPort); 
//   me.bind(localAddr); 
      me = new DatagramSocket(myPort, InetAddress.getByName(myIP)); 
      Msg("Bound Successfully."); 
      return true; 
     } catch (SocketException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      Msg(e.getMessage()); 
     } catch (UnknownHostException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      Msg(e.getMessage()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return false; 
    } 

private String GetCurrentIP(){ 
    WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE); 
    return Formatter.formatIpAddress(wifiMgr.getConnectionInfo().getIpAddress()); 
} 

public void Msg(String msg){ 
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); 
    Log.v(">>>>>", msg); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 
} 

C#客戶端...

public partial class Form1 : Form 
{ 
     Socket me; 
     EndPoint myEndPoint; 

     byte[] inBuffer, outBuffer; 

     EndPoint serverEP; 

     private void SendToClient() 
     { 
      if (serverEP == null) 
      { 
       serverEP = new IPEndPoint(IPAddress.Parse(textBoxsip.Text), int.Parse(textBoxsp.Text)); 
      } 
      try 
      { 
       lock (me) 
       { 
        outBuffer = new byte[256]; 
        outBuffer = Encoding.Default.GetBytes(textBoxmsg.Text); 
        me.SendTo(outBuffer, serverEP); 
       } 
       Task.Run(() => MessageBox.Show("Sent")); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private String GetCurrentIP() 
     { 
      IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); 
      var selectedIPs = from ip in ips 
          where ip.AddressFamily == AddressFamily.InterNetwork 
          select ip; 
      return selectedIPs.First().ToString(); 
     } 

     public Form1() 
     { 
      InitializeComponent(); 

      inBuffer = new byte[256]; 
      outBuffer = new byte[256]; 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      this.Text = GetCurrentIP(); 

      me = new Socket 
      (
       AddressFamily.InterNetwork, 
       SocketType.Dgram, 
       ProtocolType.Udp 
      ); 
     } 

     private void buttonBind_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       myEndPoint = new IPEndPoint(IPAddress.Parse(textBoxBip.Text), int.Parse(textBoxBp.Text)); 
       me.Bind(myEndPoint); 
       Task.Run(()=> MessageBox.Show("Bound Successfully.")); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void buttonReceiveFrom_Click(object sender, EventArgs e) 
     { 
      if (serverEP == null) 
      { 
       serverEP = new IPEndPoint(IPAddress.Parse(textBoxsip.Text), int.Parse(textBoxsp.Text)); 
      } 
      try 
      { 
       me.BeginReceiveFrom 
       (
        inBuffer, 
        0, 
        inBuffer.Length, 
        SocketFlags.None, 
        ref serverEP, 
        new AsyncCallback(onReceiveComplete), 
        null 
       ); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void onReceiveComplete(IAsyncResult ar) 
     { 
      try 
      { 
       int nobs = me.EndReceiveFrom(ar, ref serverEP); 

       if (nobs > 0) 
       { 
        AddtoListBox(Encoding.Default.GetString(inBuffer)); 
       } 

       inBuffer = new byte[256]; 

       me.BeginReceiveFrom 
       (
        inBuffer, 
        0, 
        inBuffer.Length, 
        SocketFlags.None, 
        ref serverEP, 
        new AsyncCallback(onReceiveComplete), 
        null 
       ); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void AddtoListBox(String msg) 
     { 
      this.Invoke((Action)delegate(){listBox1.Items.Add(msg);}); 
     } 

     private void buttonSendTo_Click(object sender, EventArgs e) 
     { 
      SendToClient(); 
     } 
} 
} 
+0

以及我配發的研究完成,並試圖萬噸代碼,但沒有得到success.Its在夜裏2點,我厭倦了這個時並不想寫一個大的材料,所以好心幫助 –

+0

只是回答我應該提供什麼ip給c#客戶端 –

回答

0

這裏是一個很好的C#< - > Android的UDP例如: Android client finding C# server automatically

C#

//receive UDP packet 
       int port = (int)float.Parse(Variables.port_key); 
       UdpCient UDP_packet = new UdpClient(port); 
       UDP_packet.EnableBroadcast = true; 
       IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); 
       IPAddress from_addr = null; 
       Boolean gogo = false; 
       while (!gogo) 
       { 
        Byte[] receiveBytes = UDP_packet.Receive(ref RemoteIpEndPoint); 
        string returnData = Encoding.UTF8.GetString(receiveBytes); 
        if (returnData.ToString() == "83hcX1") 
        { 
         gogo = true; 
        } 
        from_addr = RemoteIpEndPoint.Address; 
       } 
       //send UDP packet 
       IPEndPoint ipEndPoint = new IPEndPoint(from_addr, port); 
       Byte[] sendBytes = Encoding.UTF8.GetBytes("94dbF5"); 
       UDP_packet.Send(sendBytes, sendBytes.Length, ipEndPoint); 
       UDP_packet.Close(); 

的Android

    //send UDP packet 
        DatagramSocket UDP_packet = new DatagramSocket(SERVERPORT); 
        UDP_packet.setBroadcast(true); 
        byte[] b = "83hcX1".getBytes("UTF-8"); 
        DatagramPacket outgoing = new DatagramPacket(b, b.length, getBroadcastAddress(Main.this), SERVERPORT);     
        UDP_packet.send(outgoing); 
        //receive UDP packet 
        boolean gogo = false; 
        while (!gogo) {      
         byte[] buffer = new byte[1024]; 
         DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);  
         UDP_packet.receive(incoming); 
         String message = new String(incoming.getData(), 0, incoming.getLength(), "UTF-8"); 
         if (message.equals("94dbF5")) { 
          gogo = true; 
          SERVER_IP = incoming.getAddress(); 
         }     
        }    
        UDP_packet.close(); 

InetAddress getBroadcastAddress(Context context) throws IOException { 
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    DhcpInfo dhcp = wifi.getDhcpInfo(); 
    if (dhcp == null) { 
      return null; 
     } 
    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; 
    byte[] quads = new byte[4]; 
    for (int k = 0; k < 4; k++) 
     quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); 
    return InetAddress.getByAddress(quads); 
} 

有些路由器(也許5%)阻止UDP廣播,所以......要小心。

取得Android(服務器)IP:

InetAddress getBroadcastAddress(Context context) throws IOException { 
     WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
     DhcpInfo dhcp = wifi.getDhcpInfo(); 
     if (dhcp == null) { 
       return null; 
      } 
     int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; 
     byte[] quads = new byte[4]; 
     for (int k = 0; k < 4; k++) 
      quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); 
     return InetAddress.getByAddress(quads); 
    } 
+0

謝謝你mgulan –