简体   繁体   English

从Android手机向PC(Windows)发送udp消息不起作用

[英]send udp message from android phone to PC(windows) not working

I want to send a UDP message from my android phone 4.2(client) to PC(server) using WIFI connection. 我想使用WIFI连接从我的Android手机4.2(客户端)向PC(服务器)发送UDP消息。 My phone and PC are connected via wireless router. 我的手机和PC通过无线路由器连接。 But no message is received from phone to mobile. 但是没有收到从手机到手机的消息。 I have also tested this code for PC to PC connection successfully. 我也已经成功测试了此代码以实现PC到PC的连接。 I have added internet permission to manifest.xml. 我已将Internet权限添加到manifest.xml。 I would be greatefull, if you could help me. 如果您能帮助我,我将不胜感激。 Thank you. 谢谢。 I have added this permission. 我已添加此权限。

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Client: 客户:

@Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        Button button1 = (Button) findViewById(R.id.button1);
        final TextView tv = (TextView) findViewById(R.id.textView1);
        final TextView tv2= (TextView) findViewById(R.id.textView2);







        button1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) 
            {

                boolean morgan= isOnline();
                String s = String.valueOf(morgan);
                tv.setText(s);


                try{

                    //InetAddress ipaddress = InetAddress.getByName("localhost");
                    InetAddress ipaddress = InetAddress.getByName("192.168.10.11");
                    int port = 6500;
                    //byte[] buffer = new byte[1024]; // empty byte array
                    String msg ="hello goooooooogle"; // send this message to the server
                    byte [] b_array = msg.getBytes();

                    //on SERVER side DatagramSocket able to receive packets on 8080 port
                    DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number)
                    DatagramSocket socket = new DatagramSocket();
                    socket.send(packet);
                    socket.close();

                }
                catch(Exception e)
                {
                    System.out.println(e);
                }
                }




        });   
    }

    public boolean isOnline() {

        Runtime runtime = Runtime.getRuntime();
        try {

            Process ipProcess = runtime.exec("/system/bin/ping -c 1 192.168.10.11");
            //Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);

        } 
        catch (IOException e)         
        { e.printStackTrace(); } 
          catch (InterruptedException e) { e.printStackTrace(); }

        return false;
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Server 服务器

public class server 
{
    public static void main(String args[])
    {

        try{
            System.out.println("aaa");
            byte[] inbuf = new byte[1000]; // default size
            DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);

            DatagramSocket socket = new DatagramSocket(6500);
            socket.receive(packet);

            int numBytesReceived = packet.getLength();
            System.out.println(numBytesReceived);
            String s = new String(inbuf);
            System.out.println(s);
            //System.out.println(inbuf[2]);

            socket.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

When dealing with network operations on Android it is recommended to use a separate thread to perform such operations. 在Android上处理网络操作时,建议使用单独的线程来执行此类操作。 So try isolating your code in the onClick() method into an AsyncTask to run it in the background. 因此,请尝试将onClick()方法中的代码隔离到AsyncTask中,以在后台运行它。

private class SendMessageTask extends AsyncTask<String, Void, Void> {
 protected Void doInBackground(String... ip) {
     // run network socket code here
     return null;
 }
}

Then onClick() will contain something like this: 然后onClick()将包含以下内容:

new SendMessageTask().execute("IP_HERE");

Obviously you can modify it to fit your needs. 显然,您可以对其进行修改以适合您的需求。 However, if you need to send more data during the lifetime of your app, you may want to use your own background thread. 但是,如果您需要在应用程序的生命周期内发送更多数据,则可能需要使用自己的后台线程。 Here's a more detailed explanation to why network operations can't / shouldn't be done in the UI thread - http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html 以下是有关为什么/不能在UI线程中进行网络操作的详细说明-http: //www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

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

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