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
Related
Im working on building my own GUI program that talks to my pc from a tablet. I have the server side done in java but my problem is on the client side.
I want to send data out the PrintWriter to the server from a separate method.
I have accomplished sending in the code below (it sends 'a') but i cant figure out how to send it from a separate method. i believe its a basic java scope problem that im not understanding. i would really appreciate the help.
I have tried moving the variables into other scopes.
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) {
String hostName = "192.168.0.3";
int portNumber = 6666;
try ( //Connect to server on chosen port.
Socket connectedSocket = new Socket(hostName, portNumber);
//Create a printWriter so send data to server.
PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
//Send data to server.
dataOut.println("a");
}catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
public static void sendToServer() {
//I want to control the print writer from this method.
//I have failed i all the ways i have tried.
}
}
You could move the Printer-Code (try try block) into the sendToServer-method and call it via
TestClient client = new TestClient();
client.sendToServer("this is a test");
Of course the sendToServer method needs to accept a parameter then. Even better would probably be to put the main method into a Starter class and decouple it from the Client-Class that you use for sending the data.
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.
I am looking to get/read the Data I passed after I connected a couple of Android Devices, so far I pair, connect and transmit the information between them, but not sure how to implement the reading part, here I am not sure if I should use createRfcommSocketToServiceRecord or listenUsingRfcommWithServiceRecord to create the reading socket for this purpose.
I have two screens, one where the user push a button and transmit the info and the other where the receiver press another button and read the data, I wonder if the sync is incorrect and after I push the "send" button and then the "read" button the connection is unavailable or if this implementation is just not recomendable all together.
These are my two attempts:
Attempt 1:
//Executed after the user press the read data button
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(device.getName(),uuid);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
BluetoothSocket clientSocket = serverSocket.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
Attempt 2:
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
//clientSocket without method and invoke is not working either
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
On serverSocket.accept() or clientSocket.connect() I get the exception:
Connection is not created, failed or aborted
I would appreciate if anyone could guide me towards getting the data reading part working. Thanks.
Take a look at Android's BluetoothChat example included with the Android SDK. I think it does exactly what you want.
$ANDROID_SDK/samples/android-19/legacy/BluetoothChat/src/com/example/android/BluetoothChat
Read the managing the connection part.
Its clearly written in the documentation how to exchange (read/write) info between devices through Bluetooth. http://developer.android.com/guide/topics/connectivity/bluetooth.html
I'm trying to make a Java interface to send some AT commands to a GPRS Module.
I already had a working interface on Processing, but I migrated to pure Java because I find it easier to make graphic interfaces.
The Processing program sends data over serial to COM#. COM# is an Arduino with a GPRS Shield. All the Arduino Code does is pass the data received to the GPRS module and viceversa:
void loop(){
if (GPRS.available())
{
while(GPRS.available())
{
buffer[count++]=GPRS.read();
if(count == 64)break;
}
Serial.write(buffer,count);
clearBufferArray();
count = 0;
}
if (Serial.available()){
delay(100);
while(Serial.available()){
GPRS.write(Serial.read());
}
}
}
So I know that works fine because I've tested it using the Processing interface, and an external tool called SSCOM and all the comands are interpreted correctly.
Now the problem is, that when I tried to make the interface on java, using RXTX, it's not working at all. I'm not getting any errors on the console, and the only data I'm receiving on the Arduino is ΓΏ (char 255) each time I run java, and it's being sent when opening the port, not when writing to the serial port.
Here's the SerialHandlerclass I'm using. I found it around the web.
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialPortHandler {
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public void connect(String portName) throws IOException, PortInUseException, NoSuchPortException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);
// Get the port's ownership
serialPort =
(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
outStream = serialPort.getOutputStream();
inStream = serialPort.getInputStream();
} catch (NoSuchPortException e) {
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
serialPort.close();
throw e;
}
}
/**
* Get the serial port input stream
* #return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}
/**
* Get the serial port output stream
* #return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}
/**
* Sets the serial port parameters
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 19200;
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException ex) {
throw new IOException("Unsupported serial port parameter");
}
}
}
And here's my main class:
public class Main {
SerialPortHandler serial = new SerialPortHandler();
serial.connect("COM3");
OutputStream serialOut = serial.getSerialOutputStream();
String s = "AT+CPOWD=0\r\n";
serialOut.write(s.getBytes());
serialOut.flush();
}
}
rxtxSerial.dll and RXTXcomm.jar are in jre\bin and jre\lib\ext respectively.
I can't find the problem, like I said, I don't get any errors or warnings anywhere.
I'm using NetBeans 7.3.1, JDK 1.7 and Windows 8.1 x64.
I also tried using jSSC but I get the same results.
I solved the problem. It wasn't the jSSC or RXTX library.
PeterMmm was right, I needed a delay, but I needed it on my java program.
When I was testing communication, I was opening the port and sending data right away. The problem is Arduino by default resets when a connection is established, so the Arduino wasn't ready to process it.
A couple days ago, I decided to try again, with jSSC, but this time, the java program asked for an input to send through the serial port, leaving time for Arduino to boot. Arduino successfully received anything I typed.
Now that I implemented serial communication on the user interface I was developing, everything runs smoothly.
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. ;-)