سؤال

I'm trying to send a simple string from an android device to a pc. I managed to send the string via wifi (because is on a LAN network), but the code doesn't work over 3g. The code i'm using is this:

class send extends AsyncTask
        {

            @Override
            protected Object doInBackground(Object... params) {
                try {

                    InetAddress serverAddr = InetAddress.getByName("IP here")
                    Socket socket = new Socket(serverAddr, 8564);
                    String message = "sample_message";
                    try {
                        PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
                        out.println(message);   

                    } catch(Exception e) {}
                    finally {
                        socket.close();
                    }
                } catch (Exception e) {}
                return null;
            }
        }
هل كانت مفيدة؟

المحلول

Where is your PC connected? Is it a LAN behind NAT? Are you using the LAN IP address as serverAddr? What is "IP here"?

If you are using a local network IP address behind the NAT you'll never be able to connect.

If you have a router/wifi AP, enable port forwarding to you PC and use the public IP address provided by the ISP as serverAddr.

نصائح أخرى

Have you tried creating a DataOutputStream like

DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
dos.writeBytes(message + '\n');

Instead of :

PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
                        out.println(message);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top