I'm trying to connect to a simple Java server on my computer (in the future a true server, but I'm just learning how to program with sockets first. When I try to connect, the application on the phone throws an IOException. However, on the emulator, it does NOT.
I do have:
< uses-permission android:name="android.permission.INTERNET"/>
included in the manifest. And here's the code block that's executed when I hit open:
try {
responseField.setText("Opening socket...");
Socket socket = new Socket(getIP(),Integer.parseInt(getPort()));
responseField.setText("Socket opened. Initializing out...");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
responseField.setText("Done. Initializing in...");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
responseField.setText("Done.");
} catch (NumberFormatException e1) {
responseField.setText("NumberFormatException");
} catch (UnknownHostException e1) {
responseField.setText("UnknownHostException");
} catch (IOException e1) {
responseField.setText("IOException");
}
Are you making sure that the server end uses a ServerSocket and uses the ServerSocker.accept() method?
So it seems that a weak Wi-Fi signal is causing error. I tried to surf the web (Google, CNN, etc.) afterward, and I could not. So I will just have to test on the emulator for now, or in a stronger signal. Thanks
If you were able to connect to the web before (I am assuming) but not after, then its not a problem with the wifi strength. Also depending on place you are surfing, the wifi router may have been configured not to allow such connections. Try to ping your server IP using a different computer within the same network and see whether you can ping. Emulator will work since the server is running on the localhost.
Related
Good day,
I have a java game that I want to play with a friend over network, I have implemented Sockets and tested the game on my pc using localhost as address, but was unable to connect to the external ip of my pal's pc, presumably due to us both being behind routers.
Here is the code of host/client:
CLIENT:
try {
socket = new Socket(inputHostIp(), 5555);
} catch (IOException e) {
e.printStackTrace();
}
SERVER:
try {
hostServer = new ServerSocket(5555);
} catch (IOException e1) {
e1.printStackTrace();
}
listenForUserConnection();
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
Socket socket = null;
try {
socket = hostServer.accept();
} catch (IOException e) {
e.printStackTrace();
continue;
}
joined(socket);
}
The exception I am getting now is
java.net.ConnectException: Connection timed out: connect
On trying to init I/O:
java.net.SocketException: Socket is not connected
java.net.Socket.getInputStream/java.net.Socket.getOutputStream
I have set up port forwarding with the chosen port number (5555) linked to the internal ip on both our machines.
What are my options for getting this to work?
ADDENDUM:
We have also tried using Hamachi to create a virtual LAN, but there seems to be an issue with that - we can’t ping one another even through that, it diagnoses with an issue -
Tunnel:
VPN domain's tap device is down
Local results:
Adapter configuration:
Cannot get adapter config
Traffic test: Cannot complete test
Peer results: [160-056-951]
Adapter configuration: OK
Traffic test: Inbound traffic blocked, check firewall settings
I have tried shutting down firewalls, hamachi issues changed to just ‘cannot get adapter config’, but otherwise no results.
On my pc, however, I got a version of windows that doesn’t seem to display Firewall setting properly, if you think it’s likely an issue, can you tip me on how to test my firewall?
We are currently trying to implement WebSocket server using Tyrus and everything went alright (server-client communication worked well) until we tried to test what happens if server initialization fails (e.g. bad port).
The underlying code throws SocketException (permission denied). The exception is written to stdout but the server proceeds and the program continues beyond start() method.
public void runServer() {
// bad port number
Server server = new Server("localhost", 10, "/websockets", null, EchoEndpoint.class);
try {
server.start();
// this line should not be printed
System.out.println("Server started");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please press a key to stop the server.");
reader.readLine();
} catch (Exception e) {
System.out.println("Exception caught");
e.printStackTrace();
} finally {
server.stop();
}
}
Is there any way to detect whether the server started successfully?
EDIT: We know we cannot use port 10 (that is why we tried it). We just need to check whether the server is running (by somehow catching the exception). (And we do not want to test it by an attempt to send some dummy data with a client - that would not really fix the problem)
Your port number '10' is too low to be used by regular user. You must be privileged user or use a port number greater than 1024:
Server server = new Server("localhost", 1025, "/websockets", null, EchoEndpoint.class)
Working on a client-server android application. The clients are polling the bufferedinputstream (in) for server messages, meanwhile also repeatedly checking if server is reachable so they can terminate instantly when server goes offline.
try {
while (true) {
if (MainActivity.in.available() > 0) {
message = MainActivity.readInput();
break;
}
Thread.sleep(100);
}
} catch (IOException e) {Log.e("myoutput", e.toString()); serverOffline = true; } //server probably offline?
catch (InterruptedException e2) {}
On one of my test devices (android 2.2) this works as I thought, as soon as I close down the server the IOException is triggered. Although on my second test device (android 4.3) the IOException is not triggered (compling with API 8). But I'm starting to think this is not a device thing as I tried running both API 8 and 18 in the emulator and it didn't trigger.
Any ideas?
I'm probably not providing all essential information to get any help from here, please let me know if so and I'll provide!
I am using the following java code in Android AVD on Windows7 to create my server with serverPort = 1131;
try {
ServerSocket serverSocket = new ServerSocket(serverPort);
serverSocket.setReuseAddress(true);
while(isRunning){
try {
final Socket socket = serverSocket.accept();
DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
serverConnection.bind(socket, new BasicHttpParams());
httpService.handleRequest(serverConnection, httpContext);
serverConnection.shutdown();
} catch (IOException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
}
}
serverSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
I get the following exception :-
01-18 06:30:03.381: W/System.err(1494): java.net.BindException: bind failed: EACCES (Permission denied)
The firewall on my machine is off & I have added special rules for that as well.
Do I need to do something special for running server on AVD on Window7?
Kindly help.
Thanks
I found the following on the MSDN site (search the site for "bind" and "EACCES"):
WSAEACCES - 10013
Permission denied.
An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto
without broadcast permission being set using setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later),
another application, service, or kernel mode driver is bound to the
same address with exclusive access. Such exclusive access is a new
feature of Windows NT 4.0 with SP4 and later, and is implemented by
using the SO_EXCLUSIVEADDRUSE option.
Thus, if we assume that the JVM native libraries map WSAEACCES to this exception, there are two obvious possible explanations:
This is a permissions-based thing. ADV doesn't have permission to bind to that port.
Some other application has already bound to the port with the SO_EXCLUSIVEADDRUSE socket option.
IMO, either explanation is plausible. (Or it could be something else ...)
I hope you can help. Im fairly new to progamming and Im playing around with java Sockets.
The problem is the code below. for some reason commSocket = new Socket(hostName, portNumber); is returning true even when it has not connected with the server (server not implemented yet!). Any ideas regarding this situation?
For hostName Im passing my local machine IP and for port a manually selected port.
public void networkConnect(String hostName, int portNumber){
try {
networkConnected = false;
netMessage = "Attempting Connection";
NetworkMessage networkMessage = new NetworkMessage(networkConnected, netMessage);
commSocket = new Socket(hostName, portNumber);
// this returns true!!
System.out.println(commSocket.isConnected());
networkConnected = true;
netMessage = "Connected: ";
System.out.println("hellooo");
} catch (UnknownHostException e){
System.out.println(e.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
Many thanks.
EDIT: new Socket(.., ..); is blocking isnt it? i thought in that case if that was processed without exceptions then we have a true connection?
EDIT: I played around with anti virus and now it is working!
Had that exact same situation a few days ago on a corporate computer, and searched for it for hours.
Check your antivirus, some antivirus (like E*** N**32) use live TCP scanning that make a connection succeed even if nothing is listening on the target port but will reset it later when you try to read/write from the socket.
Add this to your code:
commSocket.getOutputStream().write(0);
commSocket.getInputStream().read();
If you get a SocketException now, you should really consider to change your antivirus.
Alternatively, set a breakpoint in your application right after creating the socket, and then use netstat -ano (on Windows) to check which process id is associated with the other endpoint of your socket (which should be on your machine if you connect to localhost).
I would suggest you to disable your antivirus, but in some cases even that does not help to unload their broken live TCP scanning driver...
The Socket constructor connects right away and will throw an IOException if it doesn't succeed. So apparently you have connected successfully to a server (this could be one you didn't make yourself).