Android Bluetooth sending file problem - java

I am writing a small program to send file between Android and PC through bluetooth. I already
read the bluetooth chat example in google android site.
Currently, my version works really well with sending a text message via bluetooth, but when I send some files, around >= 20 KB, it stops working and throwing EOFException as below:
java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.readFully(ObjectInputStream.java:2716)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1665)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1340)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1963)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1887)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at com.test.pcserver.BluetoothServerListener.run(BluetoothServerListener.java:74)
at java.lang.Thread.run(Thread.java:636)
Currently, my java program on the PC using bluecove-2.1.0
Here are my main codes:
In Android:
// Get the BLuetoothDevice object
if (BluetoothAdapter.checkBluetoothAddress(address)) {
device = mBtAdapter.getRemoteDevice(address);
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
socket = device .createRfcommSocketToServiceRecord(ProgramConstants.BLUETOOTH_UUID);
socket.connect();
out = new ObjectOutputStream(socket.getOutputStream());
// Send it to PC
out.writeObject(contentObject);
out.flush();
}
In My PC, I read it:
PC Version, server
StreamConnectionNotifier streamConnNotifier = null;
// Create the service url
String connectionString = "btspp://localhost:" + ProgramConstants.BLUETOOTH_UUID.toString()
+ ";name=myappname";
// open server url
streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
while (true) {
// Wait for client connection
StreamConnection connection = streamConnNotifier.acceptAndOpen();
ObjectInputStream in = new ObjectInputStream(connection.openInputStream());
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
// read string from spp client
DataInController data = new DataInController(model);
data.processDataIn(in.readObject(), dev.getBluetoothAddress());
}

You need to add after flushing the outputstream
out.close();
otherwise the stream can become corrupted.

Related

android DatagramChannel tunnel must connect to a server in VpnService?

I'm coding a VPN in android for watch the local network traffic (packet) and let the packets go after inspection. my app is base on ToyVPN, so far i can receive the packets but i can't send them Through the tunnel. i see the tunnel connects to ('127.0.0.1',9040). My question is, is needed a server to bind on ('127.0.0.1',9040) to respond to other tunnel side? if not? where does the tunnel connect to? Basically how this tunnel works?
see a part of the code:
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("MyVPNService")
.addAddress("192.168.1.0", 24)
.addDnsServer("8.8.8.8")
.addRoute("0.0.0.0", 0).establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 9040));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
tunnel.configureBlocking(false);
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET_SIZE);
Log.d("hixnal","tunnel open:" + tunnel.isOpen() + " connected:" + tunnel.isConnected());
//e. Use a loop to pass packets.
int timer = 0;
int p=0;
while (true) {
boolean idle = true;
int length= in.read(packet.array());
if (length > 0) {
p++;
Log.d("hixnal",p+"");
packet.limit(length);
//debugPacket(packet);
//tunnel.write(packet);

Android client app not connecting to a server on pc

I have the following problem... I am writing a system consisting of a Server side - on my pc and a Client side on my lovely Xperia (a.k.a. an Android phone). The problem is that when I attempt to bind my phone to the pc, through the client app, the logcat says:
failed to connect to /*xxx.xxx.x.xxx (port 2002): connect failed: ETIMEDOUT (Connection timed out)
*here goes my ip address, it starts with 192...
Actually I use a try - catch on the client side, within the try I set the socket but the problem is that the process fails, I guess, to create the socket properly as it goes in the catch block... I am running both devices on my home Wi-Fi hotspot. As I said I use sockets, which probably means that the type of my connection is TCP (? :) ). Please suggest some kind of a solution to this because the more I continue reading in forums (here as well), the more I get confused.
A snipped of my code:
public class ClientSide extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params){
final String SERVER_HOSTNAME = "xxx.xxx.x.xxx";
final int SERVER_PORT = 2002;
BufferedReader mSocketReader;
PrintWriter mSocketWriter;
final String TAG = ClientSide.class.getSimpleName();
String data="";
String outputln = "Me. Android";
try {
Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mSocketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Connected to server " + SERVER_HOSTNAME + ":" + SERVER_PORT);
//Reads from the socket
data = mSocketReader.readLine();
//Writes to the socket, a.k.a. sends info
mSocketWriter.println(outputln);
mSocketWriter.flush();
} catch (IOException ioe) {
System.err.println("Cannot connect to " + SERVER_HOSTNAME + ":" + SERVER_PORT);
ioe.printStackTrace();
}
return data;
}
Thank you in advance, if you need more info I will do my best to provide it. I am an extreme beginner in the Android dev, sorry for my English.
*Update: The server side app is written in java, too build of 6-7 classes, I don't run all that through Apache or any of these. I don't want to just test my app, I want a real connection over the wi-fi, not through the usb.
try this: open control panel -> Windows Defender firewall -> allow an app or feature through Windows defender firewall (on left) -> check on Apache HTTP server and mysqld for private and public networks
👍👍👍

Data sent via Bluetooth turns up multiple times while new data continue to be received

I'm trying to build an android client application that sends data regarding gestures that the user performs, to a Java server, using Bluetooth.
When the user performs a gesture, the app sends data about it to the pc.
For example (android client send) 5:-24:2, (java server receive) 5:-24:2.
As long as the gestures are performed long range between themselves, the code works fine.
The problem is when the app sends data very fast (because the user perform a scroll for example, so onScroll(...) called for each onTouchEvent(...)).
Then a specific message gets stuck:
(android client send) 5:-24:2, (java server receive) 5:-24:2 (ok)
(android client send) 5:-24:2, (java server receive) 5:-24:2 (ok)
(android client send) 5:-24:2, (java server receive) 5:-24:25:-24:2 (message stuck)
(android client send) 5:-24:2, (java server receive) 5:-24:25:-24:2 (message stuck)
...
The java server side read code:
private StreamConnection mConnection;
public void run() {
try {
InputStream inputStream = mConnection.openInputStream();
System.out.println("waiting for input");
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
inputStream.read(buffer);
String command = new String(buffer).trim();
System.out.println(command);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The android client write side:
private final OutputStream mmOutStream;
String msg = "5:-24:2";
byte[] msgByte = msg.getBytes();
mmOutStream.write(msgByte);
One major error I did was to use the same buffer while inputStream.read(buffer) received data in varied lengths.
I did the following change and that solved many of the problems.
int length;
while (true) {
length = inputStream.read(buffer);
String command = new String(buffer, 0, length);
System.out.println(command);
}

Desktop server and android client local connection

i try to connect my windows desktop java server from android client. I'm working cross-platform. Desktop server and desktop client working fine with same code, but desktop server and android client has a interesting problem. manifest permissions is setted.
Desktop java server code
ServerSocket serverSocket = new ServerSocket(tcp_port);
Socket link = null;
while(true) {
link = serverSocket.accept();
PrintWriter output = new PrintWriter(link.getOutputStream(),true); // flush true
BufferedReader input = new BufferedReader(new InputStreamReader(link.getInputStream()));
// step 1 password auth
String message = input.readLine(); // wait password
if(message.equals(password)) {
output.println("correct");
message = null;
message = input.readLine(); // wait udp port request
if(message.equals("UDP")) {
output.println(udp_port+"");
etc
.
.
Android client code
Socket link = null;
link = new Socket(hostip,tcp_port);
PrintWriter output = new PrintWriter(link.getOutputStream(),true); // auto flush true
BufferedReader input = new BufferedReader(new InputStreamReader(link.getInputStream()));
while(true) {
// step1 send the password wait the response
output.println(password);
String message = input.readLine(); // password response
if(message.equals("correct")) {
output.println("UDP"); // request udp
message = null;
message = input.readLine();
udpport = Integer.parseInt(message);
etc
.
.
My problem is same code works fine on java desktop client and java desktop server but
when i try to connect java desktop server from android client password auth part works fine but
output.println(udp_port+""); send data two times when i looked to the server side it sends empty string firstly and then sends my value what is wrong ?
message = null;
message = input.readLine(); // wait udp port request
if(message.equals("UDP")) {
it reads the empty string and jump the if statement but if i use
message = null;
message = input.readLine(); // read empty string
message = input.readLine(); // read my data
if(message.equals("UDP")) {
statement works
This is expected behavior if you try to read the data before it has been received - something that is more likely to occur when receiving from a remote system, but always a possibility you must allow for.
Your application must wait until a full message has been collected, in this case probably by looping on the readLine() call until you get a non-null message.

Blackberry HTTP Connection Issue

I have a simple app written the connects to web service (restful). The app works fine on the blackberry simulator however I'm having problems using it on a blackberry 9300.
I keep getting the error "java.io.ioexception: tunnel down" when the apps attempts to call the web service.
The service I am calling is a simple HTTP post and I'm trying to run this over WIFI (the WIFI connection is working fine for browsing the internet).
I'm using a connection string of "http://127.0.0.1:8080/test/restws;interface=wifi" with the IP address changed to the actual Ip address of the server I'm calling. I can call the restful web service on this server on my laptop browser fine.
The code Im using is similar to below & works fine on the simulator. The only thing im changing between the simulator and the code on the phone is the connection string (using "interface=wifi" as oppose to "deviceside=true")
Is this a code problem or is it a setting I need to change on the handset? Any ideas on what I need to do to overcome this.
Thanks
StreamConnection s = (StreamConnection) Connector
.open(connectionString);
httpConn = (HttpConnection) s;
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Length", Integer.toString(postData.length()));
OutputStream output = httpConn.openOutputStream();
output.write(postData.getBytes());
output.flush();
output.close();
String response = httpConn.getResponseMessage();
int statusCode = httpConn.getResponseCode();
if (statusCode != HttpConnection.HTTP_OK) {
}
InputStream is = httpConn.openInputStream();
int ret = 0;
while ((ret = is.read(buf)) > 0) {
os.write(buf, 0, ret);
}
result = new String(os.toByteArray());
I had problems in here .After getting HttpConnection everything is the same i guess. Try this:
ConnectionFactory cf = new ConnectionFactory();
ConnectionDescriptor cd = cf.getConnection("YourUrl");
httpConnector = (HttpConnection) cd.getConnection();
httpConnector.setRequestMethod(HttpConnection.POST);

Categories

Resources