简体   繁体   中英

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:

//SERVER
ServerSocket serverSocket = new ServerSocket(1234);
Socket s1 = serverSocket.accept();
PrintStream ps = new PrintStream(s1.getOutputStream());
ps.println("text");

My client code:

//CLIENT
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

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