Reputation: 571
I am working on an app,I have made a TCP Listner which is working fine on wifi network but when i am connected to 3G/4G or mobile network it does not work.Can some body help me here? my code is here
public class ListenerService extends Service {
Socket socket;
private ServerSocket serverSocket;
BufferedReader in = null;
static String message=null;
int portNo=1619;
boolean flag=true;
final static String MY_ACTION = "MY_ACTION";
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new Task().execute();
}
private class Task extends AsyncTask <Void, String, String> {
@Override
protected String doInBackground(Void... params) {
try {
serverSocket = new ServerSocket(portNo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (flag) {
try {
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
//try {
StringBuilder total = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
total.append(line);
}
message = total.toString();
Log.d("NETWORK-RECEIVE", "Message!:" + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("Server Startd","Listener Serverice is running");
//Toast.makeText(getApplicationContext(),"Service Started", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
can some tell me what m i missing here?
Upvotes: 1
Views: 2619
Reputation: 5911
You are trying to connect two devices over TCP connected to two different subnets. That's impossible. You are pretty much asking the question: "Why can my friend hear me when he's standing in front of me, but not if he's in another room?" The only way to make that work is to open the door. But you'd have to implement this "door", which is called NAT traversal or "hole punching" and really is a different communication concept (check Android P2P (direct-connection) over the Internet (behind NAT) and Android: NAT Traversal?).
In the end, there are three solutions to your problem:
Edit:
It sounds like you have a web server that is trying to connect to an Android device running the code above. That would be option 1, but still, an Android device can't be reached over the Internet. As far as I know, you have to turn that around: The device has to register itself on the server so that the server can kind of "connect" other devices to it.
Upvotes: 3