简体   繁体   中英

Android programming with Sockets

I am currently trying to write a very simple app that sends an object using sockets from my android phone to my simple server. I have wrote the server to receive the object, which at the moment is only receiving a Date object, had tested it with a simple client program from my laptop and the server is working but I can't get the android version to connect. If I could get some guidance would really be appreciated. I have provided my code below. Thanks.

    public class Test03 extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.test03);

            final Button gpsSend = (Button)findViewById(R.id.gpsSend);

            gpsSend.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            // Contact Date Server
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            Socket socket = null;
            Date date = null;

            try{
                socket = new Socket("igor.gold.ac.uk", 3000);
                oos = new ObjectOutputStream(socket.getOutputStream());
                ois = new ObjectInputStream(socket.getInputStream());
                date = (Date) ois.readObject();
                DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
                textView.setText(formatter.format(date));
                oos.close();
                ois.close();
            }
            catch(Exception e){
                textView.setText(e.getMessage());
            }
        }
    });
}
}

Thanks for the help turns out that Jin35 was right. I hadn't included internet permissions in the manifest file.

So for any other newbies you have to add the following line to the manifest.xml

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

use e.printStacktrace() instead of getMessage(). It's better to debug.

Thanks for the help turns out that Jin35 was right. I hadn't included internet permissions in the manifest file.

So for any other newbies you have to add the following line to the manifest.xml

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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