This works in the earlier version of my app, which is basically the exact same code. The only difference is the current app uses a higher build tools and sdk compiled version, would that cause the code to error? Also the app extends FragmentActivity instead of Activity now.
One of the errors is a null pointer exception, which from logcat is due to the ServerSocket (ss) being null.
The other error is libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use) at the line 8 in the snippet
I have tried implementing ss.setReuseAddress(true), however it doesn't work due to an unresolved symbol issue?
Any idea or pointers would be greatly appreciated!
class CommsThread implements Runnable {
private volatile boolean stopFlag = false;
private ServerSocket ss ;
private static final int SERVERPORT = 6000;
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT); <-- bind error here
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG,"IO Error here"); <--- this is printed in log
}
try {
s = ss.accept(); <----- nullpointer exception here
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myHandler.sendEmptyMessage(0);
while(stopFlag == false){
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.printf(String.valueOf(d.format(accel[0]))+"\t"+String.valueOf(d.format(accel[1]))+"\t"+String.valueOf(d.format(accel[2])) + "\tAccelerometer" + "\n");
out.printf(String.valueOf(d.format(gyro[0]))+"\t"+String.valueOf(d.format(gyro[1]))+"\t"+String.valueOf(d.format(gyro[2]))+ "\tGyroscope" + "\n");
out.printf(String.valueOf(d.format(magnet[0]))+"\t"+String.valueOf(d.format(magnet[1]))+"\t"+String.valueOf(d.format(magnet[2]))+"\tMagnetometer"+ "\n\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if( s==null)
{
stopComms();
}
*/
}
}
The NPE is due to nothing but your own faulty code structure. The real issue is the bind exception, which means something else is listening at port 6000, possibly a prior instance of the same application. Fix that, or use another port.
Related
I am creating new connection class for Bluetooth device on Android Studio.I cant figure out why thrown exception in design time.
public ConnectingThread(BluetoothDevice device,MainActivity activity,BluetoothAdapter adapter) {
mainActivity=activity;
bluetoothAdapter=adapter;
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
The line:
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
has the potential to throw a NoSuchMethodException. You do not have a catch block to handle this exception. So you have to add another catch block under your existing catch block as follows:
catch(NoSuchMethodException e){
//Insert code here
}
Also, that line of code will later throw the following exceptions so it is best to handle them as well: IllegalAccessException, and InvocationTargetException. Thus, your try-catch blocks should be as follows:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
catch(NoSuchMethodException ex){
//Insert code here
}
catch(IllegalAccessException e){
//Insert code here
}
catch(InvocationTargetException e){
//Insert code here
}
Alternatively, you could handle every single exception with the general Exception class. In this case, your code should look something like this:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (Exception e) {
//Enter code here
}
I'm trying to do an Over The Air firmware update for the Bluegiga BLE121LR Bluetooth module.
I'm getting all the way to the characteristic write (it's supposed to be a write_no_repsonse type) and that's where it just hangs up and seems to kick itself out of the while loop and I get the "The application may be doing too much work on its main thread." warning in my logcat output.
I'm executing the following code in onResume after making sure my radio connection is established. The OTA file is in the assets folder and seems to load into the byte array properly.
I'm very much a novice and I'm sure there's a threading convention or something that I'm missing here. Can anyone point me in the correct direction?
try {
InputStream dis;
try {
dis = getAssets().open("BLE121LR_OTA.ota");
byte[] fileData1 = new byte[dis.available()];
try {
this.wait(200);
dis.read(fileData1);
int length = fileData1.length;
Log.i(TAG, "Length of file: " + length);
int i = 0;
if (mService != null) {
otaDataChar = mService.getCharacteristic(IOPENER_OTA_DATA);
otaControlChar = mService.getCharacteristic(IOPENER_OTA_CONTROL);
while (i < length) {
byte[] byte16 = new byte[16];
System.arraycopy(fileData1, i, byte16, 0, 16);
Log.e(TAG, "byte16" + getHexString(byte16));
otaDataChar.setValue(getHexString(byte16));
otaDataChar.setWriteType(4);
mConnectedGatt.writeCharacteristic(otaDataChar);
Log.e(TAG, "CHAR WRITE");
i = i + 16;
}
} else {
Log.e(TAG, "Mservice fucked up.");
}
Log.e(TAG, "BEGIN FLASH REBOOT");
// otaControlChar.setValue("3");
// mConnectedGatt.writeCharacteristic(otaControlChar);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (Exception e) {
}
And it had nothing to do with threading...I was trying to operate on a null.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm having trouble using the sockets library.
import java.io.*;
import java.net.*;
public class SocketAdapter{
Socket mySocket=null;
PrintWriter out=null;
BufferedReader in=null;
public SocketAdapter(String host,int port){
try {
InetAddress serverAddr = InetAddress.getByName(host);
mySocket = new Socket(serverAddr, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(mySocket.getOutputStream(), true);
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeto(String data){
out.println(data);
}
public String readdata(){
String fromSocket=null;
try {
fromSocket = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// blocking
return fromSocket;
}
public void close(){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I access this class via a 2nd thread in my main activity. In the debugger the value of mySocket is always null. I have no idea what I'm doing wrong but I'm pretty sure its something basic.
EDIT: Turns out it the sockets object was null because of an IOException triggered by the app not having internet permission.
in the manifest fixed it.
There's not much point in catching exceptions in constructors. It just misleads the rest of the code into assuming that the object has been completely constructed, when it hasn't. Change the constructor to throw those exceptions and remove all the try/catches, and catch the exceptions accordingly at the calling sites. Then you can never get a null Socket reference from this code again.
use Socket variable as static may be it will work.
static Socket mySocket = null;
or
use a separate function to get the socket Connection.
public Socket getSocketConnection(String strServerIP , int iPort)
{
try
{
Socket s = new Socket(strServerIP,iPort);
return s;
}
catch (Exception e)
{
return null;
}
}// End getSocketConnection Method.
If you are working multiple threads, you need to be synchronized over the contractor.
You can implement it by your self or define the SocketAdapter class instance as volotile.
Also please read this
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.
I'm currently working on a tcp client in Android.
I want to connect my android device to a tcp server on my computer and receive the data once every 2 seconds. The problem is that I'm getting force close on my application because of the while loop that I've implemented in the tcp client.
I've tried writing in different ways the loop that will make the tcp client checking the server socket, but with no success. How can make a loop that will check the server socket without getting the force close?
Here's my code that I'm currently using:
public class Connection implements Runnable {
#Override
public void run() {
try {
sk=new Socket(server,port);
viewsurface.setText("connected");
flag = true;
} catch (UnknownHostException e) {
viewsurface.setText("failed 1 socket");
flag = false;
} catch (IOException e) {
viewsurface.setText("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
viewsurface.setText(received);
} catch (IOException e) {
viewsurface.setText("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
viewsurface.setText("checkin failed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You need to paste the exception that you are getting to cause the force close, before anyone can provide decent help.
But some suggestions that might solve the problem.
Most likely to be the problem, viewText.setText can only be called from the UI thread. There's quite a few ways to handle this. You can use AsyncTask or if you have an Activity reference you can use runOnUIThread and pass in a runnable that calls setText.
Move checkin = sk.getInputStream(); to before the loop. There's no reason to get the strem every cycle through the loop.
Do not create the BufferedReader every cycle through the loop. Move it before the loop
.sleep(2000) does not guarantee exactly 2 seconds.
I'm having some code formatting issues so I apologize.
private class DownloadFilesTask extends AsyncTask<Void, String, Void> {
protected Long doInBackground(Void... nothing) {
try {
sk=new Socket(server,port);
publishProgress("connected");
flag = true;
} catch (UnknownHostException e) {
publishProgress("failed 1 socket");
flag = false;
} catch (IOException e) {
publishProgress("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
publishProgress(received);
} catch (IOException e) {
publishProgress("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
updateProgress(
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
protected void onProgressUpdate(String... progress) {
viewsurface.setText(progress[0]);
}
protected void onPostExecute(Void result) {
//nothing
}
}