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
Related
so i'm trying to do something a little unusual, it's just for fun. I have a game i created using libgdx, it consists of a ship that can shoot. What i want to do is to use some external push buttons to move it. The push buttons send signals to arduino, which in turn sends them to an HC-05 bluetooth module. however i'm very doubtful about the android side of things. What i did basically was the following:
Because i'm working on libgdx i created an interface called BluetoothDude, with three methods setBluetooth() (which will set the bluetooth for the particular platform),String whatIsTheMessage() (which will tell you what's been sent to the phone), and boolean isActive(), to know if the bluetooth is active of course.
The MainGame will receive a BluetoothDude so that particular classes like Ship have access to the Message and are able to react to it.
Then i did the particular implementation of Bluetooth for android, in the setBluetooth() i followed this guide very closely: https://developer.android.com/guide/topics/connectivity/bluetooth.html
i'm sure it is connecting properly, because when it creates the socket it can print "connection success with HC-05" (it will only print that if the method which creates the sockets, which i called BTConnect() returns true).
The problem seems to be in reading the data, the code i'm using is
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Handler handler;
public ConnectedThread(BluetoothSocket socket,Handler mHandler) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
handler = mHandler;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
i made an object of this class in setBluetooth like this
if (device != null) {
if (BTconnect()) {
isActive = true;
connectedThread = new ConnectedThread(socket,handler);
System.out.println("connection success with" + device.getName() + " message: " + message );
}
i have a lot of doubts
first what is the target here, the mHandler was created in BluetoothDude, so is that the target?, second i'm quite sure the thread isn't even running because if i put a line like System.out.println("run") inside run() it doesn't show me the line like a trillion times in the logcat when the app is executed. What is wrong with it, i hope you can help me, i'm not very experienced at all of this, and it's driving me crazy.
I cannot see if this is the case from your code but if you are calling platform specific methods, that should be done in the platform specific project subproject.
For more information on how to do that you can check out this page :
https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
So if your LibGDX game has a function say, "setBluetooth" each platform will have its own implementation of said method. That will differ when you compile for Android or iOS.
If you try to call platform specific code in your core game probably won't work.
Hope it helps, maybe you have already done that in which case you can ignore my comment.
I'm developing an app to exchange data between an Android phone and a pc. I've chosen xml-rpc as a way to communicate, and as a library i downloaded android-xmlrpc (https://code.google.com/p/android-xmlrpc/).
When I call remote procedures from my phone, I use the XMLRPCClient and it works almost fine.
But then I have to synchronize data from my server to the application, so I need to listen on a given port and wait for a xmlrpc request.
I tried the following code:
protected Void doInBackground(Void... params) {
try { ServerSocket socket = new ServerSocket(8888);
XMLRPCServer server = new XMLRPCServer();
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
}
} catch (Exception e) { Log.v(LOG_TAG, "Server: Error", e); }
return null;
}
But it seems it never receives any procedure call. I mean, to debug it I'm trying to use my XMLRPCClient as follow:
XMLRPCClient client = new XMLRPCClient("http://127.0.0.1:8888/");
Object o = client.call("add",1,3);
Log.v(LOG_TAG, o.toString());
And I always get no response. It's stuck on readMethodCall and never reads that the method I requested is "add"... It's strange it gets stuck there. Can't figure the reason why it is stucked here. Do you have any idea ?
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'm working on a web project, I have a class named Connection, this class establishes a connection via TCP/IP with another device, When there is a http get request I instance an object "connection_o" and start a thread to keep the communication up like this: "connection_o.start" so the connection is established, in the next http request I must send a message, but when I execute again the "doGet" in order to avoid the nullpointer exception I need to instance the object again , but I can't because I need to use the same instance that I used before that is running, in my tests, the connection keeps working but I´m unable to access to the thread I already created. So I need some kind of static class or a way to use the thread that is already running.
This is the code for the socket
import java.io.*;
import java.net.*;
public class Provider extends Thread{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider(){}
public void run()
{
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
do{
try{
message = (String)in.readObject();
// System.out.println("client>" + message);
if (message.equals("cambio la variable"))
System.out.println("Abriendo Puerta");
// sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
// System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
This is the doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = request.getParameter("s");
//Routine to send blink to RPi
if (s.equals("Start")){
Provider c = new Provider();
c.Inicio();
}
if (s.equals("Send")){
c.sendMessage("Blink");
}
Thanks in advance
The problem I assume is, that HTTP is a stateless protocol. That means by default the server does not know anything about the client.
That is where Sessionscome in place. On your initial request you have to initialize a session for the client who made the request. From then you are able to "recognize" the client on requests (e.g. to restore the clients state).
You also have to save the "connection" inside the session context. You may want to consider using so called "Connection Pools" because it could be very complicated to handle all established connection and close them properly (e.g. session timeout etc.)
I suggest you read basics about the HTTP protocol, Sessions and (e.g. Database)Connetion-Handling.
May be you can keep the
Provider c = new Provider();
as an instance variable of the servlet class and change the code :
if (s.equals("Start")){
c.Inicio();
}
Note : In this case you need to take care of the thread safety. Because now c.Inicio() would be called by multiple request threads at a time.
I have a working Java client/server program which is very straightforward and basic. This works fine. However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. I am using almost identical code for the android networking code as I use for the normal client. My android code is simple, all it does is starts this thread from onCreate:
private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;
private Thread clientThread = new Thread("ClientThread") {
#Override
public void run() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
DataInputStream din = new DataInputStream( socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
while (true) {
String message = din.readUTF();
setPicture("picture1");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). When I run my normal pc client with the same port and IP address, the connection goes through. But when I run this code on my android device, the socket timesout when I try to connect.
Does anyone have any suggestions for where I am going wrong?
Double check that you added the permission requirement in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
But, possibly more importantly, 192.168.x.x is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? If you're on mobile, try it from wifi.