Android UDP 入站通讯

标签: Android
发布时间: 2014/8/30 12:44:50
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想保持侦听 UDP 端口上 23000,应用程序工作良好的本地 environment 。但切换到 3g 有没有机会,交通阻塞。

我试着上前接收相同的端口发送 4 个字节的数据载波通道的 ' 开放':

                InetAddress serverAddr = InetAddress.getByName(SOULISSIP);
                DatagramChannel channel = DatagramChannel.open();
                socket = channel.socket();

                //socket = new DatagramSocket();
                socket.setReuseAddress(true);

                //InetSocketAddress ia = new InetSocketAddress("localhost", SERVERPORT);
                InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
                socket.bind(sa);
                DatagramPacket holepunh = new DatagramPacket(new byte[]{0,1,2,3},4, serverAddr, SERVERPORT);
                socket.send(holepunh);

                // create a buffer to copy packet contents into
                byte[] buf = new byte[200];
                // create a packet to receive


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

                Log.d("UDP", "***Waiting on packet!");
                socket.setSoTimeout((int) opzioni.getDataServiceInterval());
                // wait to receive the packet
                socket.receive(packet);
                UDPSoulissDecoder.decodevNet(packet);
                socket.close();

有没有简单的方法打开通道和接收 UDP 数据报在 23000 端口上吗?

解决方法 1:

所以,答案是在请求中,虽然我一直纠结于接收套接字。我不得不将发件人向本地端口用于接收套接字绑定数据报:

            //send                
            serverAddr = InetAddress.getByName(SOULISSIP);

            DatagramChannel channel = DatagramChannel.open();
            sender = channel.socket();
            sender.setReuseAddress(true);

            //amateur hole punch
            InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
            sender.bind(sa);
            //stuff to send
            List<Byte> macaco = new ArrayList<Byte>();
            macaco = Arrays.asList(pingpayload);
            ArrayList<Byte> buf = buildVNetFrame(macaco, prefs);
                    //someone help me here...
            byte[] merd = new byte[buf.size()];
            for (int i = 0; i < buf.size(); i++) {
                merd[i] = (byte) buf.get(i);
            }
            packet = new DatagramPacket(merd, merd.length, serverAddr, SOULISSPORT);
            sender.send(packet);

接收器和发件人是在单独的线程上使用相同的本地端口。.setReuseAddress(true)允许这。

官方微信
官方QQ群
31647020