I am trying to setup a client-server system with the Pi acting as the server, and the Android device being the client. Every time I run the code (I cobbled together from the internet) the client throws an IOException:
Connection timed out: connect
I just discovered that when I try to ping the Pi's IP it is unreachable.
How can I fix this?
Note I am currently testing Java code on a Windows PC until I get it working.
Client Code (Java):
import java.io.*;
import java.net.*;
public class client
{
static Socket clientSocket;
static String homeIp="192.168.0.105"; //internal ip of server (aka Pi in this case)
static int port=4242;
public static void main(String [] args)
{
sendToPi("I sent a message");
}
public static void sendToPi(String s)
{
//wordsList.append("in sendToPi()\n");
System.out.println("in sendToPi()");
//Log.e("aaa","in sendToPi()\n");
try {
clientSocket = new Socket(homeIp, port);
PrintStream out = new PrintStream(clientSocket.getOutputStream());
out.println(s);
} catch (UnknownHostException e) {
//Log.e("aaa","Don't know about host: "+homeIp+"."+e.getMessage());
System.out.println("Don't know about host: "+homeIp+"."+e.getMessage());
//System.exit(1);
} catch (IOException e) {
//Log.e("aaa","Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
System.out.println("Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
//System.exit(1);
}
}
}
Server Code (C): I used code from here exactly as written. compiled as server. Started with ./server 4242
In my case the solution was to explicitly forward the client port in my router.
Related
I m trying to create a simple test application that connect via Socket to my computer (in localhost).But it thows some exception and I can't figure out how to solve it. NOTE: I m running the apk in my phone (not in an emulator)
Java Server Code
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run(){
System.out.println("Server is running and listening ... ");
try{
ServerSocket ss = new ServerSocket(7000);
while(true){
Socket s = ss.accept();
System.out.println("Connesso");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from Client: "+ dis.readUTF());
dis.close();
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
};
t.start();
}
}
And this is the
Andorid Client Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button sendBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBTN=(Button)findViewById(R.id.button);
sendBTN.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run(){
try {
System.out.println("Starting Connection");
Socket s = new Socket("127.0.0.1", 7000);
System.out.println("Connection DONE");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Let's Test The Socket");
dos.flush();
dos.close();
s.close();
System.out.println("Closing socket");
} catch (UnknownHostException e){
System.out.println("There was an Unknown Erorr:");
e.printStackTrace();
} catch (IOException e) {
System.out.println("There was an IOException:");
e.printStackTrace();
}
}
};
t.start();
Toast.makeText(this, "Messagge Sent...", Toast.LENGTH_SHORT).show();
}
}
What I get it this error:
I also tried some other ports like 1432 or 8000 or 8080 but the result is the same
Then I tried to change the IP from 127.0.0.1 to my own PC ip.. and what I get is this error..
EDIT:
I tried to run the app inside an Emulator using 10.0.2.2 as IP and everything woks fine.. I also tried to use my Private Ip in another JAVA Client program and it works fine.. So the problem is just the connection beetween my real phone and my PC (even if they are in the same network)
Make sure the IP when set to use your local machine from the emulator is 10.0.2.2
When you are using your phone and your PC:
If you are on the same network, make sure you're using the appropriate IP for your PC on your network as the server connection host. I usually set my physical machines to static IPs on my network (through my router) so I don't have to constantly look at what they are, but this is by no means a requirement.
If you are using your phone off of your home network, you will have to use the IP your ISP gives to connect, and make sure that the port is forwarded appropriately in your router if you have one set up.
In either case, you'll need to make sure the firewall is allowing incoming connections on the port you are specifying.
Ok I found the solution.
Then I deleted the exception I ve made in my firewall for port 7000 and I created a new exception which allow the connection using port 3000 and now it works fine.
If you're trying to connect the localhost listening server via Android Virtual Device, you must first check whether the "mobile data" in the AVD is in "On" state, since it doesn't work if it is in "Off" state, well I don't know the exact reason but it works like that.
I'm using Netty to build a client-server network communication. Is it possible to find out to which app a client has connected to in case of success?
It's the following problem I try to solve: If a Tomcat Server is listening to port 8080 my client app successfully connects to the "server". Looks like it doesn't matter who is listening to the port.
How can I find out if my server app is currently started and listening to the port instead of e.g. Tomcat?
This is the connection code of the client:
public void run(){
//disconnectTest();
createBootstrap( new Bootstrap(), new NioEventLoopGroup(), true);
}
public void createBootstrap( Bootstrap b, EventLoopGroup eventLoop, boolean initialAttempt){
mWorkerGroup = eventLoop;
try {
b.group(mWorkerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(new ClientChannelInitializer());
logger.info("Connecting client...");
b.connect(mHost, mPort)
.addListener( new ConnectionListener(this, initialAttempt));
} catch (Exception e) {
logger.error("Failed to connect client to server '" +mHost +": " +mPort +". Error: ", e);
}
}
Snippet from the ConnectionListener:
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("success");
}else{
System.out.println("error");
}
}
EDIT:
If you want check the availability of the server withing the client App, you can use certain tools that Java7 can give us, for example, using this code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
This does not have to be a specific function Netty. More info here:
Sockets: Discover port availability using Java
Enjoy.
To check it outside you client app:
To test the server status I use the Hercules software client.If you know that server will respond someting, using hercules you can send a dummy data y wait the server response.
How you can see, Hercules, allows too makes a ping to the server :)
Hope it helps.
I am trying to connect with a Biometric Fingerprint Attendance Device using a Java program. The device I am using is a Biocom Fingerprint attendance system. However, I am search and reading about that and I see the SDK could used which based on device type (which hard, not logical, moreover, it is not global solution!)
I research for a global standard on how to connect, send and retrieve data with a Fingerprint Device which again I wasn't lucky enough to find a clear solution. Currently, I tried to connect with the device by creating a Socket object (through Ethernet port) but also not executed with me. This open infinite loop problems on my head.
Is there any general, standard way to connect, send and retrieve data from such device using Java?
Can a Socket be considered as a solution for such problem?
If yes, what is wrong in my code below? What additional things more than the host IP and port number are needed to connect with the device?
The Socket code that used:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester() {
}
void run() throws IOException {
try {
// 1. creating a socket to connect to the server
requestSocket = new Socket("192.168.0.19", 4370);
System.out.println("Connected to given host in port 4370");
// 2. get Input and Output streams
in = new ObjectInputStream(requestSocket.getInputStream());
// 3: Communicating with the server
String line;
while (true) {
line = in.readLine();
if (line != null) {
System.out.println(line);
}
}
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception Exception) {
Exception.printStackTrace();
} finally {
in.close();
requestSocket.close();
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("client: " + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) throws IOException {
Requester client = new Requester();
client.run();
}
}
This image may give more details:
You don't need the ObjectInputStream. Just use the InputStream you get from requestSocket.getInputStream().
Alternatively use a terminal programm like putty to connect to your device. This requires no coding.
Biocom Biometrics are ZKTeco devices. ZkTeco devices are launched only with windows SDK. You can download the SDK from https://www.zkteco.com/en/download_catgory.html and use the DLL in java which can run only on Windows platorm. For HTTP communication, to work in any platform through any language, refer http://camsunit.com/application/zk-teco-essl-api-integration.html
I am trying to establish two-communication between one server and two clients. This works very well when all programs run on the same machine but it doesn't work when I try using LAN network.
I got the error :
java.rmi.ConnectException: Connection refused to host: 192.168.1.24; nested exception is:
java.net.ConnectException: Connection timed out: connect
Here is the server code :
public class Server{
private Game partie; // The class Game extends UnicastRemoteObject and implements ServerInterface
public Server() throws RemoteException {
System.setProperty("java.rmi.server.hostname", "192.168.1.24");
partie = new Game();
LocateRegistry.createRegistry(1099);
try{
Naming.rebind("Server", partie);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String argv[]) throws RemoteException{
new Server();
}
}
Here is the constructor of the client code :
public Client(String aName, String aServerAdress) throws RemoteException {
super();
name = aName;
ServerAdress = aServerAdress; // = "192.168.1.24"
theRegistry = LocateRegistry.getRegistry(ServerAdress);
try {
serverInterface = (ServerInterface) theRegistry.lookup("Server");
} catch (NotBoundException e1) {
e1.printStackTrace();
}
try {
theRegistry.bind(name, this); // For two-way communication
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
serverInterface.registerClient(name);
}
Where registerClient(String name) code is approximately (in Game class) :
cd_client = (ClientInterface) Naming.lookup("rmi://127.0.0.1/" + name);
All firewalls are disabled.
I have been working on this problems for many hours and I have still not found what is wrong. I would really appreciate if you could help me a bit.
Thank you
Change all occurances of 127.0.0.1 (except registry binding) to your LAN IP address (192.168.1.24 in your case)
127.0.0.1 is a Loopback address:
"Loopback (loop-back) describes ways of routing electronic signals,
digital data streams, or flows of items from their originating
facility back to the receiving end of the source without intentional
processing or modification. This is primarily a means of testing the
transmission or transportation infrastructure."
-- from Wikipedia
I have been trying to get a simple networking test program to run with no results.
Server:
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(String[] args) {
final int PORT_NUMBER = 44827;
while(true) {
try {
//Listen on port
ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
System.out.println("Listening...");
//Get connection
Socket clientSock = serverSock.accept();
System.out.println("Connected client");
//Get input
BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
System.out.println(br.readLine());
br.close();
serverSock.close();
clientSock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Client:
import java.io.*;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws IOException {
final int PORT_NUMBER = 44827;
final String HOSTNAME = "xx.xx.xx.xx";
//Attempt to connect
try {
Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
//Output
out.println("Test");
out.flush();
out.close();
sock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.
I purposely picked such an uncommon port to see if that was the problem, with no luck.
I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out.
I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.
When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.
I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.
These problem comes under the following situations:
Client and Server, either or both of them are not in network.
Server is not running.
Server is running but not listening on port, client is trying to connect.
Firewall is not permitted for host-port combination.
Host Port combination is incorrect.
Incorrect protocol in Connecting String.
How to solve the problem:
First you ping destination server. If that is pinging properly,
then the client and server are both in network.
Try connected to server host and port using telnet. If you are
able to connect with it, then you're making some mistakes in the client code.
For what it's worth, your code works fine on my system.
I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue, which is more possible than you might think. I'd test your ISP.
Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.
I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?
I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/
But I still couldn't get this accessed over public IP, working on it now...
I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.
My first (not so elegant) solution was to stop the client for a while using the sleep method:
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry.
This is my method:
private Socket createClientSocket(String clientName, int port){
boolean scanning = true;
Socket socket = null;
int numberOfTry = 0;
while (scanning && numberOfTry < 10){
numberOfTry++;
try {
socket = new Socket(clientName, port);
scanning = false;
} catch (IOException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return socket;
}
As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.
Your code should become:
Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }
This solution helped me, I hope it helps you as well. ;-)