Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

App to connect to java socket on laptop

  • 29-10-2011 04:36PM
    #1
    Registered Users, Registered Users 2 Posts: 1,180 ✭✭✭


    Hi I am starting off making apps, and as a test i'm sending a string from my android to a java socket server running on my laptop. both are connected to the same wifi but i will want it to work on 3g and other wifis also

    here is my java code:
    //makes a socket listening on port 4242
                ServerSocket serverSocket = new ServerSocket(4242);
                System.out.println("RUNNING");
                String output;
    
                while(true){
                    Socket socket = serverSocket.accept();
                    
                    InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
                    BufferedReader reader = new BufferedReader(streamReader);
                    
                    output = reader.readLine();
                    System.out.println(output);                
                }    
    
    snippet of code not executing in android app:
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.final_year_project);                
            try{
                //connect to socket(server)   
                Socket socket = new Socket("<my_ipaddress>", 4242);
                //Socket socket = new Socket("10.0.2.2", 4242);
                
                //for writing to server
                DataOutputStream outToServer = new                  DataOutputStream(socket.getOutputStream());
               
                outToServer.writeBytes(output + '\n');
    
                socket.close();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
    
    android permissions:
    <uses-permission
            android:name="android.permission.INTERNET" />
    
    This works on the emulator if i use the 10.0.2.2 address, nothing works on the phone. i assume i have to do some port forwarding? can somebody please talk me through it please?


Advertisement