如何解决我的android Udp套接字有时没有收到数据包?

时间:2015-08-31 07:08:31

标签: c# android udp

首先,我知道使用UDP套接字而不是TCP的风险。

我将客户端C#中的图像发送到正在使用UDP套接字侦听特定端口的服务器Androids。

问题是我有时会在第一次发送时收到数据包(注意:运行C#控制台图像发送应用程序)。但有时候,为了接收它,必须尝试多次发送尝试。

任何帮助或想法将不胜感激。提前致谢

C#客户端代码

        const int Port = 4800;
        string serverIp = "?";

        //Get all addresses
        string hostname = System.Net.Dns.GetHostName();
        IPHostEntry allLocalNetworkAddresses = Dns.Resolve(hostname);

        //Walk thru all network interfaces.
        foreach (IPAddress ip in allLocalNetworkAddresses.AddressList)
        {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


            //Allow sending broadcast messages
            client.SetSocketOption(SocketOptionLevel.Socket,
            SocketOptionName.Broadcast, 1);

            //Bind on port 0. The OS will give some port between 1025 and 5000.
            client.Bind(new IPEndPoint(ip, 0));

            //Create endpoint, broadcast.
            IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, Port);



            string path = "D:\\download.jpg";
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            byte[] data = br.ReadBytes(Convert.ToInt16(fs.Length));
            client.SendTo(data, AllEndPoint);              


            Console.Write("Client send 'image' to " + AllEndPoint.ToString() +
            Environment.NewLine);
         }

Android服务器

   protected String doInBackground(String... arg0) {
        final TextView text2 = (TextView) findViewById(R.id.textView2);     
       try {
            socket = new DatagramSocket(PORT);         
           int buf= socket.getReceiveBufferSize();
           byte[] receivedata = new byte[buf];
            while (true) {
                final DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
                Log.d("UDP", "S: Receiving...");

                socket.receive(recv_packet);

                byte[] buff = recv_packet.getData();



                final Bitmap new_img = BitmapFactory.decodeByteArray(buff, 0,
                        buff.length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        text2.setText("Now you are connected");                         
                        ImageView image = (ImageView) findViewById(R.id.imageView);
                        image.setImageBitmap(new_img);
                    }

                });

            }
        }
        catch (Exception e) {
            Log.e("UDP", "S: Error", e);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //tv.setText("Error Occured");
                }
            });
        }

    return text1;
}

0 个答案:

没有答案