我正在处理从蓝牙传感器接收数据的应用程序,我需要将该数据传递到在本地计算机上运行的服务器套接字。收到的数据大约是每秒40条消息。
首先,我首先尝试通过为每次写入使用单独的AsyncTask来解决它,打开套接字,写入数据并关闭套接字,并且它工作正常,但提出了一些性能问题,所以我不得不找到另一个解决方案
我编写了一个使套接字连接保持活动状态的服务,但是当我尝试将数据写入套接字时,每次写入时都会出现断管错误。
以下是该服务的代码:
public class SocketService extends Service {
public static final String SERVERIP = "10.64.64.197";
public static final int SERVERPORT = 4444;
private DataOutputStream out;
private Socket socket;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
Runnable connect = new connectSocket();
new Thread(connect).start();
}
public void sendMessage(byte[] message) {
try {
out.write(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
class connectSocket implements Runnable {
@Override
public void run() {
try {
Log.e("connectSocket", "Connecting...");
socket = new Socket(SERVERIP, SERVERPORT);
try {
out = new DataOutputStream(socket.getOutputStream());
Log.e("connectSocket", "Done.");
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
socket = null;
}
我调用sendMessage方法的代码:
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
try {
mSocketService.sendMessage(txValue);
} catch (Exception e) {
Log.e(TAG, "data_available");
}
}
我现在已经坚持了一段时间,所以任何帮助都会受到赞赏!