Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Very basic app to create a socket

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Location
    Italy
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Very basic app to create a socket

    Hi. I'm new to java/android programming, but you sure will know it by just reading the post, as I think it has to be a very simple issue for an experienced programmer.

    What I am trying to get:
    An application with 2 ToggleButtons. On click they have to connect to a socket over the LAN and send a few characters (to an Arduino board which is listening).

    What I've got after some days:
    Android SDK, Eclipse and AVD installed and running.
    An application with 2 ToggleButtons which responds to mouse clicks and shows a Toast.
    There are a main activity and a class to handle the onClick event.
    I tried in many ways but still can't get it to create a socket and send 2 characters.

    I can connect to the Arduino from my PC with a telnet client, and even from my smartphone using an example telnet app i found over the internet, and Arduino accepts the commands, so I think (I'm quite sure) the problem is not in the Arduino program.
    In order to debug my app I cut off all non essential code lines, just trying to open a socket and send a fixed string "A1". Here is what remains, but when it runs in AVD, on click shows a Toast saying "Generic ERROR", so it's not "UnknownHost" neither "IO" Exception.

    Cutting off other code lines I found that the error raises on the line which creates the socket
    socket = new Socket("192.168.1.123",80);
    The IP address and the port numbrer are correct, I can connect there using telnet.
    What's wrong with it?


    import android.os.Bundle;
    import android.app.Activity;
    import android.widget.ToggleButton;
     
    public class MainActivity extends Activity {
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
     
    		ToggleButton toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
    		toggleButton1.setOnClickListener(new MioClickListener());
     
    		ToggleButton toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
    		toggleButton2.setOnClickListener(new MioClickListener());
    	} //onCreate
    } //MainActivity

    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import android.view.View;
    import android.view.View.OnClickListener;
    //import android.widget.ToggleButton;
    import android.widget.Toast;
     
    public class MioClickListener implements OnClickListener {
     
    	@Override 
    	public void onClick(View view) {
    		Socket socket;
    		PrintWriter out;
     
    		try {
    			socket = new Socket("192.168.1.123",80);
    			out = new PrintWriter(
    					new BufferedWriter(
    					new OutputStreamWriter(socket.getOutputStream())),true);
    			out.println("A1");
    			out.close();
    			socket.close();
    		} catch (UnknownHostException e) {
    			Toast.makeText(view.getContext(), "UnknownHostException",
    				Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (IOException e) {
    			Toast.makeText(view.getContext(), "IOException",
    				Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (Exception e) {
    			Toast.makeText(view.getContext(), "Generic ERROR",
    				Toast.LENGTH_SHORT).show();
    			e.printStackTrace();
    		}
    		}
    }


  2. #2
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Very basic app to create a socket

    Hmmmmm, the Socket class throws four different possible exceptions with that particular Socket constructor.

    Your catches for UnknownHostException and IOException aren't catching it. It can't be IllegalArgumentException as the host isn't null. Add a catch block for SecurityException. That could be thrown if a security manager exists and its checkConnect method doesn't allow the operation. See if it still goes into the Exception catch block after adding that or if it was indeed a SecurityException.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Very basic app to create a socket

    Can you look at what is in logcat for error messages?
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Oct 2013
    Location
    Italy
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very basic app to create a socket

    Done. Catching SecurityException and IllegalArgumentException too. Still doesn't work.
    So I changhed IP address to an invalid one (my LAN is not connected to internet).
    Toggled comments on some lines, leaving just the socket one.
    App doesn't catch UnknownHostException, still toasts "Generic ERROR".

    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import android.view.View;
    import android.view.View.OnClickListener;
    //import android.widget.ToggleButton;
    import android.widget.Toast;
     
    public class MioClickListener implements OnClickListener {
     
    	@Override 
    	public void onClick(View view) {
    		Socket socket;
    		PrintWriter out;
     
    		try {
    			socket = new Socket("19.68.1.7",2000);
    			//out = new PrintWriter(
    			//		new BufferedWriter(
    			//		new OutputStreamWriter(socket.getOutputStream())),true);
    			//out.println("r1");
    			//out.close();
    			socket.close();
    		} catch (UnknownHostException e) {
    			Toast.makeText(view.getContext(), "UnknownHostException",Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (IOException e) {
    			Toast.makeText(view.getContext(), "IOException",Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			Toast.makeText(view.getContext(), "IllegalArgumentException",Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			Toast.makeText(view.getContext(), "SecurityException",Toast.LENGTH_SHORT).show();			
    			e.printStackTrace();
    		} catch (Exception e) {
    			Toast.makeText(view.getContext(), "Generic ERROR",Toast.LENGTH_SHORT).show();
    			e.printStackTrace();
    		}
    		}
    }

    More details:
    App's running in an AVD, not in a phisical device.I don't think this is the issue, as another app runs and works from the same AVD. This is the app (I used only the client part) that works fine:
    Android Socket Example | Examples Java Code Geeks
    They use Threads, I'm not able to do that yet.

    Perhaps something wrong in Manifest.xml? I added
    <uses-permission android:name="android.permission.INTERNET" >
    <uses-permission android:name="android.permission.ACCESS_NETWORK_ST ATE" >

    Attached: AVD screenshot and logcat file. I cleaned up the log, uploaded the app (Run As -> Android application), clicked on the first togglebutton and then clicked again on it. Two times "Generic ERROR".


    One more question:

    I looked at the documentation
    Socket | Android Developers
    the constructor Socket(string, int) only throws UnknownHostException and IOException.
    As they say Socket extends Object I looked at Object too, but still can't find SecurityException.

    Then I found
    Socket (Java Platform SE 7 )
    Why on constructor syntax there are 2 exceptions:
    public Socket(String host, int port) throws UnknownHostException, IOException
    and in the descripiton there are 4? The last 2 are optional and the first 2 you MUST catch?

    Is the documentation on docs.oracle.com more complete and reliable than developer.android.com? Should I use that?

    I saw you must import UnknownHostException and IOException, but you can catch SecurityException and IllegalArgumentException without importing them (java.lang.....). Why?
    Is there a tutorial I can read about it?
    Attached Images Attached Images
    Attached Files Attached Files

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Very basic app to create a socket

    You should copy and paste the logcat contents in the thread and not use attachments that require downloads.
    They use Threads, I'm not able to do that yet.
    Android does not allow some tasks to be done in the main GUI thread. You should study how to put the network code on another thread.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Oct 2013
    Location
    Italy
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very basic app to create a socket

    Ok for the logcat in the text. Next time I'll do.
    I already tried with threads but can't get it. No idea it could be the problem, I thinked it was possible to open a client socket from anywhere in the app.
    Now I start searching documentation, I'll try and understand how it works and soon will have this app working fine! (...I hope so...)
    Thanks.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Very basic app to create a socket

    The site you posted the link to has some examples on how to use threads:
    Android | Examples Java Code Geeks

    Besides using threads, you might need to see how to pass data read on the thread to the GUI thread so it can be shown. That site also has examples of how to do that.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Oct 2013
    Location
    Italy
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very basic app to create a socket

    I just found a lot of examples. That was the problem, the app is running fine now, sends characters to the server.
    Now I go further in studying the topic, then I have to improve the app and to add a lot of functionalities. I saw threads cannot directly work with GUI, I'll go study how to send data to the main activity or to others threads.
    Thanks for the tip, I saved a lot of time knowing what to search for.
    Here is the code of the working app, for those who are experiencing the same problem:

    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import android.view.View;
    import android.view.View.OnClickListener;
     
    public class MioClickListener implements OnClickListener {
    	@Override 
     
    	public void onClick(View view) {
    	    new Thread(new Runnable() { 
    	        public void run(){
    	    		Socket socket;
    	    		PrintWriter out;
    	    		try {
    	    			socket = new Socket("192.168.1.2", 2000);
    	    			out = new PrintWriter(
    	    					new BufferedWriter(
    	    					new OutputStreamWriter(socket.getOutputStream())),true);
    	    			out.println("With threads, it finally works!");
    	    			out.close();
    	    			socket.close();
    	    		} catch (UnknownHostException e) {
    	    			e.printStackTrace();
    	    		} catch (IOException e) {
    	    			e.printStackTrace();
    	    		} catch (Exception e) {
    	    			e.printStackTrace();
    	    		}
    	        }
    	}).start();
    	} //onClick
     
    } //MioClickListener

    Bye!

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Very basic app to create a socket

    There is an awful lot to learn in Android programming. I've only been working with Android stuff for a couple of months.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Very basic app to create a socket

    If you can (meaning if your process falls within the suggested criteria limits in the API), use AsyncTask(AsyncTask | Android Developers) instead of Threads in Android.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Create Database in Google App Engine
    By manjula in forum Java IDEs
    Replies: 3
    Last Post: June 6th, 2012, 08:02 AM
  2. How to Create a server socket to listen for incoming connections?
    By JavaPF in forum Java Networking Tutorials
    Replies: 3
    Last Post: October 28th, 2011, 09:02 AM
  3. [SOLVED] create/drop FB table from Java App
    By beruska in forum JDBC & Databases
    Replies: 1
    Last Post: October 21st, 2011, 09:51 AM
  4. speech redirection from one app to other; changing input from mic to socket
    By johnyjj2 in forum Object Oriented Programming
    Replies: 0
    Last Post: December 11th, 2009, 05:54 PM
  5. How to Create a server socket to listen for incoming connections?
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: May 5th, 2009, 08:02 AM