I’m making a client/server pair with sockets to send and receive data back and forth. When I’m at home on my internet using two separate machines for client/server, it works fine as expected. Data is transmitted and so forth.
However, today when I was working at a local coffee shop (Second Cup, in case that’s relevant), this did not work. I kept getting the following errors: either connection timed out, or no route to host.
Here is the relevant code:
Server:
public class TestServer {
public static void main(String[] args) throws Exception {
TestServer myServer = new TestServer();
myServer.run();
}
private void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
while(true) {
Socket SS_accept = mySS.accept();
BufferedReader myBR = new BufferedReader(new InputStreamReader(SS_accept.getInputStream()));
String temp = myBR.readLine();
System.out.println(temp);
if (temp!=null) {
PrintStream serverPS = new PrintStream(SS_accept.getOutputStream());
serverPS.println("Response received");
}
}
}
}
Client: (the relevant part)
//sends a command to the server, and returns the server's response
private String tellServer(String text) throws Exception {
mySocket = new Socket("192.168.0.XXX", 9999); //the IPv4 address
//use the socket's outputStream to tell stuff to the server
PrintStream myPS = new PrintStream(mySocket.getOutputStream());
myPS.println(text);
//the following code will get data back from the server
BufferedReader clientBR = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
String temp = clientBR.readLine();
if (temp!=null) {
return temp;
} else {
return "";
}
}
It’s pretty much as simple as can be. Again, as mentioned, at home on my internet it works fine – just do ipconfig, grab the IPv4 address, and put it in for the client. In coffee shops with free wifi, it doesn’t work. I even fiddled with many different ports just in case.
Thanks for any help, I’m new to sockets and finding this confusing.
192.168.x.y is a local address. source
You need your home machines ip address as the INTERNET sees it.
When you’re home next, go to http://www.whatismyip.com/ and see what it thinks you are.
Note that you might need to go onto your router and route traffic from your router to your machine for port 9999, since that’s what you’ll probably be hitting.