I have an Android application where I connect to a bluetooth device. When I shut the device off, the application tries to disconnect. So I try to close the inputstream the outputstream and the socket. Even though I have a try catch on each close try, the app crashes when it tries to close the inputstream. Any ideas? Code example:
private void resetConnection() {
if (mmInputStream != null) {
try {
mmInputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE InputStream", e);
}
mmInputStream = null;
}
if (mmOutputStream != null) {
try {
mmOutputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE OutputStream", e);
}
mmOutputStream = null;
}
if (mmSocket != null) {
try {
mmSocket.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE mmSocket", e);
}
mmSocket = null;
}
}
Any suggestions? Thanks
Related
I have the following code to connect to a Bluetooth device:
class BiSymConnectThread extends Thread {
BluetoothDevice mDevice;
public BiSymConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = mDevice.getUuids()[0].getUuid();
try {
biSymSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not connect!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
if (biSymSocket != null) {
biSymSocket.close();
}
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
try {
if (biSymSocket.isConnected()) {
biSymSocket.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IOException();
}
}
biSymSocket.connect();
eventHandler.obtainMessage(MESSAGE_CONNECT_BISYM, 0, 0, "").sendToTarget();
BluetoothConnectionService.setSocket(biSymSocket);
BluetoothConnectionService.sendMessage(biSymSocket, "S");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("Error", "InterruptedException: " + e.getMessage(), e);
throw new IOException();
}
} catch (IOException e) {
Log.e("Error", "IOException: " + e.getMessage(), e);
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT_BISYM, 0, 0, "").sendToTarget();
if (biSymSocket != null) {
try {
biSymSocket.close();
} catch (IOException e1) {
Log.e("Error", "Can't close socket!");
}
}
}
synchronized (this) {
biSymConnectThread = null;
}
}
}
If I attempt to reconnect to the device, I get the following error:
RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5
In the other question asking about this error, someone mentions the isConnected() method. However, in my case, isConnected() returns false and the connection still fails.
Does anyone know what is the problem here? It appears this is some obscure error, since there doesn't seem to be anything on the web about this.
I'm developing an Android app that is going to send camera stream to a Node.js web server by Socket. When the app has to create the socket the app doesn't execute the code inside the try statement but even though launchs any catch exception.
MyThread.java
protected Void doInBackground(Void... unused) {
OutputStream os = null;
try {Log.d("MyCameraApp", "HERE1");
mSocket = new Socket(ip, port);
if (mSocket != null) {Log.d("MyCameraApp", "SOCKET CONNECTED");
try {
os = mSocket.getOutputStream();
while (true) {
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(4);
dos.writeUTF("####");
dos.writeInt(mFrameBuffer.size());
dos.writeUTF("-##-");
dos.flush();
dos.write(mFrameBuffer.toByteArray());
dos.flush();
Thread.sleep(1000 / 15);
}
} catch (Exception e) {
e.printStackTrace();
try {
if (os != null)
os.close();
} catch (Exception e2) {
e.printStackTrace();
}
}
}
else {
Log.d("MyCameraApp", "SOCKET NULL");
}
}
catch(UnknownHostException e) {
Log.d("MyCameraApp", "CATCH SOCKET");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
CameraActivity.java
try {
mThread = new MyThread(getApplicationContext(), SERVERIP, SERVERPORT);
mThread.execute();Log.d("MyCameraApp", "WELL DONE");
}
catch(Exception e) {
e.printStackTrace();
Log.d("MyCameraApp", "CATCH");
}
The CameraActivity create a mThread object and the app only displays the log 'HERE1' inside the try, before the socket is created and then displays the log 'WELL DONE'.
I have a basic Node.js server that only is listening in the correspondent port, nothing else.
What is wrong?
Thanks in advance!
The Android device was connected by wifi and the pc was connected by Ethernet... differents subnets.
I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.
i run some code to connect to a server, send it an Object and then receive another Object.
while running this on my Android enulator (v2.2) i get - java.net.SocketException: Socket is closed
the connection to the server is successful and i'm able to send the object but when i'm trying to do socket.getInputStream() it throws the exception
this is my connector class:
public class ConnectionToServer {
UserProblemRequest sentProblem;
Problem responseProblem;
Socket socket;
public ConnectionToServer(){
sentProblem = null;
responseProblem = null;
socket = null;
}
public void connect(){
try {
Log.d(TAG, "Connecting...");
socket = new Socket(Utils.SERVER_IP, Utils.SERVER_PORT);
Log.d(TAG, "SUCCESS: Connected!");
} catch (UnknownHostException e) {
Log.d(TAG, "ERROR: Falied to connect! (UnknownHostException)");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to connect! (IOException)");
e.printStackTrace();
}
}
public void setProblemFromByteArray(byte[] data, boolean isFile){
sentProblem = new UserProblemRequest();
sentProblem.fileBArray = data.clone();
if (isFile){
sentProblem.requestType = Utils.requestType_IMAGE;
}
else {
sentProblem.requestType = Utils.RequestType_STRING;
}
}
public void sendProblem(){
ObjectOutputStream os;
try {
os = new ObjectOutputStream(socket.getOutputStream());
Log.d(TAG, "Sending file to server...");
os.writeObject(sentProblem);
os.flush();
os.close();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to send file to server!");
e.printStackTrace();
}
Log.d(TAG, "SUCCESS: File sent to server!");
}
public void closeConnection(){
try {
socket.close();
} catch (IOException e) {
Log.d(TAG, "failed to close socket");
e.printStackTrace();
}
}
public Problem reciveResponseFromServer(){
ObjectInputStream ois;
try {
ois = new ObjectInputStream(socket.getInputStream());
responseProblem = (Problem) ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return responseProblem;
}
}
and i use this code to run it:
ConnectionToServer serverConnection = new ConnectionToServer();
serverConnection.connect();
serverConnection.setProblemFromByteArray(temp_data, true);
serverConnection.sendProblem();
Problem responseProblem = serverConnection.reciveResponseFromServer();
serverConnection.closeConnection();
any ideas?
Does closing the ObjectOutputStream() in sendProblem() wind up closing the underlying socket so that when you getInputStream() in reciveResponseFromServer() the socket is already closed?
this is my class to connect and send commands to server i try separate connect code in method
but when i test the (SocketConnect) method i found it doesn't work.
my code
public class ConnAndSend {
static Socket socket = null;
static void SendCommand(String cmnd) {
DataOutputStream dataOutputStream = null;
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(cmnd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
};
}
// method to connect to server
static void SocketConnect(String SrvrIP,int SrvrPrt) {
// Socket socket = null;
try {
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
Remove the static modifier!!
Remove all the occurances of the word static
In your code:
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
you are closing the socket in finally (why?) this is wrong also!
Have you made sure your manifest file has the correct permissions?
<uses-permission android:name="android.permission.INTERNET" />
It looks like you are closing the socket before you even get a chance to use it or you are'nt calling SocketConnect before . Do you see how you you make the socket, then you close it?
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
You need to make the socket, use it to connect in your SendCommand, then close it. I'm not quite sure why you need to keep the two separate, but I believe that is your problem, you are calling close before you use the socket to connect or you simply aren't making the socket and SendCommand is using "null" to connect.