简体   繁体   中英

Android socket to Java ServerSocket Connection

I am having difficulty connecting an emulated Android Activity to a regular Java program running on my computer. Here are some of the precautions I took that should have fixed them...

  • I try to connect to 10.0.2.2, the ipaddress of the localhost that the emulator is on
  • I spawn a new thread separate from the UI thread to make the connection. (I didn't do a fancy worker thread, I simply created a new thread and said .start())

So basically thy system is composed of a normal Java program that declares a ServerSocket and then waits at the .accept() method. I kick that program off and hopefully it sits there and waits. I then switch over to my Activity class which has an onClick method of a button. That method invokes the .start() method of my new thread. Inside the .run method of my activity I declare a new Socket and try to connect to the local host.

Do you know of anything else I should be aware of? The primary problem is that nothing happens. I put a break point right after the .accept method call in the local host java program and I never reach it.

Please see this thread to connect the emulator network to the computer's network. Hope this helps

How to connect android emulator to the internet

The Top answer from the post is

I think some of the answers may have addressed this, however obliquely, but here's what worked for me.

Assuming your problem is occurring when you're on a wireless network and you have a LAN card installed, the issue is that the emulator tries to obtain its DNS settings from that LAN card. Not a problem when you're connected via that LAN, but utterly useless if you're on a wireless connection. I noticed this when I was on my laptop.

So, how to fix? Simple: Disable your LAN card. Really. Just go to your Network connections, find your LAN card, right click it and choose disable. Now try your emulator. If you're like me, it suddenly ... works! - artifex

I found this comment on the answer useful.

Actually, the emulator takes the adapter with the highest priority, so switching the priority of your adapters (wireless as highest) should work too and it won't require you to disable the LAN-adapter completely. Thanks for your answer though, saved me a headache – Anzeo Apr 6 '11 at 14:47

In your case, the Java program is on the same machine. So I thing, the Java program Socket might be binding to the IP of the one of the network interfaces and the Android is trying to connect to the other. To be sure, just disable all network interfaces except one and run your program. Post that you can adjust the priority of the network interfaces.

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