Android VpnService to capture packets won't send packet - android

I want to the new android (4.0) VpnService interface to implement simple packet capture and analysis. I have successfully capture the packet(IP packet) from the filedescriptor, but because I have no server, I want to send the packet to its original destination directly. I try to get IP and port from the packet, which are used to create protect tunnel and send packet. But when I use Fiddler to detect, I get nothing.
private Thread mThread;
private ParcelFileDescriptor mInterface;
private static String TAG = "VPN_SERVICE";
Builder builder = new Builder();
#Override
public int onStartCommand(Intent intent, final int flags, int startId) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
mInterface = builder.setSession("MyVPNService")
.addAddress("192.168.0.1", 24)
// .addDnsServer("8.8.8.8")
.addRoute("0.0.0.0", 0)
.establish();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
FileOutputStream out1 = openFileOutput("216427.txt", Context.MODE_APPEND);
ByteBuffer packet = ByteBuffer.allocate(512);
int length;
while (true){
while ((length = in.read(packet.array())) > 0){
packet.limit(length);
out1.write(packet.array());
ResolvePacket resolvePacket = new ResolvePacket();
resolvePacket.debugPacket(packet);
String desIP = resolvePacket.DESTINATION_IP;
String desPORT = resolvePacket.DESTINATION_PORT;
Log.d("IP + PORT:", "*******" + desIP + "******" + desPORT + "******");
DatagramChannel tmp_tunnel = DatagramChannel.open();
tmp_tunnel.connect(new InetSocketAddress(desIP, Integer.parseInt(desPORT)));
protect(tmp_tunnel.socket());
tmp_tunnel.write(packet);
tmp_tunnel.close();
packet.clear();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(mInterface != null){
mInterface.close();
mInterface = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}, "MyVpnRunnable");
mThread.start();
return START_STICKY;
}

Related

Wifi Direct Server/Client Connection

I am composing a WiFi Direct android app following guide of Google Developer's guide. I am just beginning to learn. I am stuck in sending an image from Client to Server. The following is Client and Server coding taken from Demo:
This is a code to call Client Intent (MainActivity):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode ==SELECT_IMAGE) {
Log.d(MainActivity.TAG, "onActivityResult Start");
Log.d(MainActivity.TAG, "requestCode "+requestCode);
Uri uri = data.getData();
Intent serviceIntent = new Intent(this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
Log.d(MainActivity.TAG, "file path " + uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_ADDRESS, IP_SERVER);
serviceIntent.putExtra(FileTransferService.EXTRAS_PORT, PORT);
this.startService(serviceIntent);
} else {
Log.d(MainActivity.TAG, "Service transfer failed");
}
}
This is code for Client (I used IntentService in a separate class):
public class FileTransferService extends IntentService {
public static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.moon.android.wifidirectproject_moon.action.SEND_FILE";
public static final String EXTRAS_ADDRESS = "go_host";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_PORT = "go_port";
Socket socket = new Socket();
public FileTransferService() {
super("FileTransferService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_PORT);
try {
Log.d(MainActivity.TAG, "Opening client socket - ");
Log.d(MainActivity.TAG, "fileUri" + fileUri);
Log.d(MainActivity.TAG, "host" + host);
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(MainActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
Log.d(MainActivity.TAG, "is - " + is);
} catch (FileNotFoundException e) {
Log.d(MainActivity.TAG, e.toString());
}
copyFile(is, stream);
Log.d(MainActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
This is a call to Server Intent
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
if (info.groupFormed && info.isGroupOwner) {
InetAddress groupOwnerAddress = info.groupOwnerAddress;
ownerIP = groupOwnerAddress.getHostAddress();
Log.d(MainActivity.TAG, "Owner connected" + ownerIP);
Intent serverIntent = new Intent(mActivity, ServerService.class);
serverIntent.putExtra("port",MainActivity.PORT);
mActivity.startService(serverIntent);
.....
The following is Server Intent Service:
public class ServerService extends IntentService {
public static String mClientIP;
public ServerService() {
super("ServerService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
Integer port = intent.getExtras().getInt("port");
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket client = serverSocket.accept();
Log.d(MainActivity.TAG, "Server: Socket opened");
Log.d(MainActivity.TAG, "clientIP" + client.getInetAddress().toString());
mClientIP = client.getInetAddress().toString();
Log.d(MainActivity.TAG, "Server: connection done");
/*
*************I am stuck here******************************
*/
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(MainActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
stopSelf();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
Lastly, the following is my LogCat. I put asterisk marks where no further progress is made in Server.
1) Server device (Initial State)
: search start
: WiFi_enabled
: Owner connected192.168.49.1
2) Client Device(sending image):
...............................
Opening client socket -
: fileUricontent://media/external/images/media/16871
: host192.168.49.1
: Client socket - true
: WiFi_enabled
: is - android.os.ParcelFileDescriptor$AutoCloseInputStream#3c520d34
3) Again Server Device
: Server: Socket opened
: clientIP/192.168.49.133
: Server: connection done
: open failed: ENOENT (No such file or directory)
I must confess that I don't fully understand the server/client. I just have rough knowledge. However, if you give me any hint on what I am wrong with, I will try to learn more for myself. I've spent several days working on it but couldn't work it out. Thanks for reading this post.

Not able to read any data from Bluetooth device in Android

I am having a bluetooth device . Basically i want my app to connect to the device and receive the data it sends.However so far i am able to connect to the bluetooth device,but i am not able to receive any inputs from it .
here is my problem:
i) DataInputStream.available() always return 0.
ii) If i use any breakpoint on line
bytes = input.read(buffer); // This will freeze doesn't show anything.
and line below it never executes
public class ConnectThread extends Thread{
final String TAG="ConnectThread";
private ReadThread mReadThread = null;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean isDeviceConnected;
public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket = null;
Handler mHandler;
BluetoothDevice bTdevice;
private DataInputStream mReadData = null;
public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
super();
this.bTdevice = bTdevice;
this.mHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
BluetoothSocket socket;
try {
socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("**** Socket created using standard way******");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
mmSocket = socket;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public synchronized void run() {
// TODO Auto-generated method stub
super.run();
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.cancelDiscovery();
Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
}
if (mmSocket != null) {
mmSocket.connect();
Log.i("***Socket Connection Successful**", "Socket Connection Successful");
isDeviceConnected = true;
mReadData = new DataInputStream(mmSocket.getInputStream());
Log.i("***Read data**", "" + mReadData);
if (mReadThread == null) {
mReadThread=new ReadThread(mReadData,mmSocket);
mReadThread.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("***Error**", "Socket Connection failed");
e.printStackTrace();
try {
mmSocket.close();
isDeviceConnected = false;
} catch (IOException closeException) {
e.printStackTrace();
}
}
// mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
// Read the data from device
private class ReadThread extends Thread {
/** The input. */
private DataInputStream input;
/**
* Constructor for ReadThread.
*
* #param input
* DataInputStream
*/
private BluetoothSocket mSocket;
public ReadThread(DataInputStream input, BluetoothSocket socket) {
this.input = input;
this.mSocket = socket;
}
/**
* Method run.
*
* #see java.lang.Runnable#run()
*/
public synchronized void run() {
try {
Log.d(TAG, "ReadThread run");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
bytes = input.available(); // always return 0
// bytes = mReadData.readInt();
Log.i("***Bytes data**", "" + bytes);// print 0
Log.i("***Data input stream**", "" + input); // Here input is not null
if (input != null) {
Log.i("***hello world**", "...");
while (isDeviceConnected) {
try {
bytes = input.read(buffer); // this code never executes
Log.i("**bytes data**", " " + bytes);
if (input != null) {
int len = input.readInt();
Log.i(TAG, "Response Length: " + len);
if (len > 65452) {// Short.MAX_VALUE*2
Log.i(TAG, "Error: Accesory and app are not in sync.");
continue;
}
Log.d(TAG, "Response Length: " + len);
Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
byte[] buf = new byte[len];
Log.d(
TAG, "input.available() " + input.available());
if (input.available() > 0) {
input.readFully(buf);
System.out.println("Output:=");
}
Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
isDeviceConnected = false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
isDeviceConnected = false;
Log.e(TAG, "catch block 3 " + e.toString());
}
}
}
}
In ReadThread.Run() - you have to move the code
bytes = input.available (); // Always return 0
into while loop
1, you use input before checking for null if (input! = null)
2, Data is sent continuously and is a high probability that when running thread do not come any data, so therefore you have to give input.available bytes = (); into a while loop.
3, You can try to modify data processing. In principle, quickly read the data in the temporary buffer, and then move to MainBuffer and then manipulated with it. An example is in c # .net Xamarin, but just for an example :
private const int BTLPacketSize = 1024;
private const int BTLdataSize = 65536;
private System.Object InternaldataReadLock = new System.Object();
private System.Object dataReadLock = new System.Object();
private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
private byte[] TempdataRead = new byte[BTLPacketSize];
private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s.
private bool continueRead = true;
public override void Run()
{
while (continueRead)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
if (e is Java.IO.IOException)
{
//.....
}
}
}
}

Communicating android and windows through socket

I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!
windows app server class:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
try
{
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
//By FMR
string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
//writeData(clientStream, response);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
clientStream.Write(msg, 0, msg.Length);
clientStream.Flush();
Console.WriteLine("\nResponed ..." + response);
}
}
catch (Exception ex)
{
Console.WriteLine("\nException while: " + ex.Message);
}
tcpClient.Close();
}
}
my android thread:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = null;
ServerSocket serverSocket = null;
Boolean bRun = true;
try {
socket = new Socket(ip, port);
if(outputStream == null) {
outputStream = new DataOutputStream(socket.getOutputStream());
}
// become server
serverSocket = new ServerSocket(port);
Log.i(G.TAG, "before serverSocket.accept");
socket = serverSocket.accept();
Log.i(G.TAG, "response recieve: ");
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
try {
serverSocket.close();
} catch (IOException e1) {
Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
}
try {
socket.close();
} catch (IOException e1) {
Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
}
}
Log.i(G.TAG, "after start recieve: ");
while (bRun) {
try {
Log.i(G.TAG, "while start: ");
String message = inputStream.readLine();
Log.i(G.TAG, "response message: " + message);
if (message != null) {
setListMessage(false, message);
}
}
catch (IOException e) {
bRun = false;
Log.e(G.TAG, "while bRun e: " + e.getMessage());
}
}
}
});
thread.start();
// in another function, my message is sent successfully from android and receive in windows
I found the problem, this line
socket = serverSocket.accept();
made the problem when I comment the line, the android app received the response!
Does anybody know why?

How to receive Digital Input from arduino using UDP in Android?

Actually I want to write a program in which whenever a button is pressed on specific digital pin of Arduino, Android receives that signal using UDP and performs tasks accordingly.
This is the Arduino code snippet:
void loop() {
buttonState = digitalRead(12);
if (buttonState == HIGH) {
// ToDo when push button is pressed
}
else {
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write("anything here");
Udp.endPacket();
}
This is my Android code:
public class Server implements Runnable
{
String serverHostname1, serverHostname2;
DatagramSocket d1;
InetAddress ip, retiip;
DatagramPacket send, rec;
String modifiedSentence;
public static String TAG = "SERVER";
DatagramSocket serverSocket;
public void run() {
Log.d(TAG, "Service Started");
try {
serverSocket = new DatagramSocket(8032);
} catch (SocketException e) {
e.printStackTrace();
}
Log.d(TAG, "Service Started");
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Log.d(TAG, "Service Started");
try {
serverSocket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
}
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
Log.d(TAG, "Service Started");
Log.d(TAG, "Received " + sentence);
}
}

NFC Pair Bluetooth Connection Android Bidirectional Socket issue

Hi I want to connect two android phones application using Bluetooth and NFC.
I am currently sending the UUID and the MAC over NFC from one device to another;
The issue is that when it comes to opening the sockets I get the following error:
java.io.IOException: Service discovery failed
On the client side of the application:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluerec);
JSONObject oneObject = null;
//NFC
Intent intent = getIntent();
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage message = (NdefMessage)messages[0];
NdefRecord record = message.getRecords()[0];
payload = new String(record.getPayload());
String add = null;
String uuid = null;
try {
oneObject = new JSONObject(payload);
add = oneObject.getString("MAC");
uuid = oneObject.getString("UUID");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(payload);
UUID uuid2 = UUID.fromString(uuid);
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
this.bluetooth = bluetooth;
BluetoothDevice device = bluetooth.getRemoteDevice(add);
connectToServerSocket(device, uuid2 );
}
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
// Block until server connection accepted.
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 e) {
Log.e("BLUETOOTH", "Blueooth client I/O Exception", e);
}
}
And on the Server side:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Bluetooth
//NFC
jsonObj = getMacAddress();
payload = jsonObj.toString();
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
String mimeType = "application/com.example.cpayvendingcomm";
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefMessage nfcMessage = new NdefMessage(
new NdefRecord[]
{
// Create the NFC payload.
new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
mimeBytes,
new byte[0],
payload.getBytes()),
// Add the AAR (Android Application Record)
//NdefRecord.createApplicationRecord("com.paad.nfcbeam")
});
nfcAdapter.setNdefPushMessage(nfcMessage, this);
initBluetooth();
}
private static final int ENABLE_BLUETOOTH = 1;
private void initBluetooth() {
if (!bluetooth.isEnabled()) {
// Bluetooth isn't enabled, prompt the user to turn it on.
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BLUETOOTH);
} else {
// Bluetooth is enabled, initialize the UI.
initBluetoothUI();
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
this.bluetooth = bluetooth;
startServerSocket(bluetooth);
}
}
private void initBluetoothUI() {
// TODO Auto-generated method stub
}
private ArrayList<BluetoothDevice> deviceList =
new ArrayList<BluetoothDevice>();
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceList.add(remoteDevice);
Log.d(TAG, "Discovered " + remoteDeviceName);
}
};
private BluetoothSocket transferSocket;
private UUID startServerSocket(BluetoothAdapter bluetooth) {
UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c545");
String name = "bluetoothserver";
try {
final BluetoothServerSocket btserver =
bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);
Thread acceptThread = new Thread(new Runnable() {
public void run() {
try {
// Block until client connection established.
BluetoothSocket serverSocket = btserver.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(serverSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = serverSocket;
} catch (IOException e) {
Log.e("BLUETOOTH", "Server connection IO Exception", e);
}
}
});
acceptThread.start();
} catch (IOException e) {
Log.e("BLUETOOTH", "Socket listener IO Exception", e);
}
return uuid;
}
// Listener for messages
private boolean listening = false;
private void listenForMessages(BluetoothSocket socket, StringBuilder incoming) {
listening = true;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
while (listening) {
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
String result = "";
while ((bytesRead == bufferSize) &&
(buffer[bufferSize-1] != 0)){
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = instream.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
incoming.append(result);
}
socket.close();
}
} catch (IOException e) {
Log.e(TAG, "Message received failed.", e);
}
finally {
}
}
Passing the Bluetooth address assumes you are connecting without prior pairing of the Bluetooth devices. Depending on whether you want to pair the two devices or not you can implement it two ways:
No Pairing. Use createInsecureRfcommSocketToServiceRecord() instead of createRfcommSocketToServiceRecord() on the client as described in how to create insecure server connection in Android. Use listenUsingInsecureRfcommWithServiceRecord() on the server.
Pairing with Secure Simple Pairing with passing OOB via NFC. It's a more involved process, beyond what you are asking.

Categories

Resources