Help! I'm trying to do some simple java socket networking in Android Studio and I can't even get in the door. The server program seems to be working ok but the android app client crashes with the error "Unfortunately InTouch has stopped" while executing the line:
sock = new Socket("Mark2015jun08", 4415);
where the hostname I put in is what is reported by the C:>hostname
command, the windows Networking Control Panel and it shows up in the DHCP table when I log into the router. It even crashes when I put in "" for a hostname which the documentation says should open a loopback. I've tried calling Socket()
a dozen different ways as you can see from my code below. I could sure use some help.
Thanks, -Mark
In the android client program I put the following try statement in the onResume()
method:
try {
//sock = new Socket("Mark2015jun08", 4415);
byte[] ip = {(byte)192, (byte)168, (byte)1, (byte)124};
//sock = new Socket(InetAddress.getByAddress(ip), 4415);
//sock = new Socket(InetAddress.getByName("192.168.1.124"), 4415);
//sock = new Socket("LOCALHOST", 4415);
sock = new Socket("", 4415);
// ommitted logic to set socket timeout and
// open object streams based on sock
} catch (IOException e){
sock = null;
log(e.toString());
}
Both Windows ipconfig and the router DHCP table both confirm my ip address but I still get the same error. Three different sources all agree on my hostname but no matter what string I put in for hostname, even "", it doesn't work. What am I doing wrong?
I use the following permissions in my Manifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This is my server program below created in Netbeans and I run it from the Windows cmd.exe
window with the command C:>java -jar intouchserver.jar
. This runs the server program on the laptop and it gets to the line
sock = serversock.accept();
and stops exactly as the documentation for accept()
explains. As far as I can tell it's listening to port 4415. (Note: I checked serversock
before this statement: it is non-null.)
package intouchserver;
import ...
public class InTouchServer {
private static ServerSocket serversock;
private static Socket sock;
public static void main(String[] args) {
try {
serversock = new ServerSocket(4415);
sock = serversock.accept();
} catch (IOException e){
System.out.println("Can't establish socket");
System.out.println(e);
System.exit(1);
}
// ommitted logic to open object streams based on sock
// and read and write to them
}
}