Daan Witte Daan Witte - 3 months ago 7
Android Question

Connecting to a server using android and Java sockets with needed permission from user

I want to connect to a server using java but the problem is that it seems nothing is working. I know this question has been asked a lot of time but non of them seem to provide a solution for this problem.

My server code:

ServerSocket serverSocket = new ServerSocket(1234);
Socket s1 = serverSocket.accept();
PrintStream ps = new PrintStream(s1.getOutputStream());

My client code:

Socket s2 = new Socket("localhost", 1234);
BufferedReader br = new BufferedReader
(new InputStreamReader(s2.getInputStream()));
String input = br.readLine();

I have added the permission tag in the android manifest:

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

What am I doing wrong. I'm not new to Java Sockets but I am new to the world of android. Do I need to run my network code in a seperate thread or what else solves my problem?

Thanks in advance

**EDIT:**I have checked the logs and console and no exception have been caught.


if you're not getting any exception on the android client this means that you're not actually opening the socket, if you do open it on the UI thread you get a NetworkOnMainThreadException. so i suspect that piece of code you posted is not being executed at all.

regarding how to do it on android it depends, if it's a short operation you can use an AsyncTask. keep in mind that one AsyncTask does not equals one Thread, they get queued up. if you need to keep the connection alive you can use a Thread. check out this example for AsyncTask and this other one for Thread. they use DatagramSocket but the idea it's the same