Communicating between C# application and Android app via bluetooth

Posted by Akki on Stack Overflow See other posts from Stack Overflow or by Akki
Published on 2012-06-23T09:13:11Z Indexed on 2012/06/23 9:16 UTC
Read the original article Hit count: 425

Filed under:
|

The android application acts as a server in this case. I have a main activity which creates a Thread to handle serverSocket and a different thread to handle the socket connection. I am using a uuid common to C# and android.

I am using 32feet bluetooth library for C#.

The errors i am facing are

1) My logcat shows this debug log

Error while doing socket.connect()1
java.io.IOException: File descriptor in bad state
Message: File descriptor in bad state
Localized Message: File descriptor in bad state
Received : Testing Connection
Count of Thread is : 1

2) When i try to send something via C# app the second time, this exception is thrown:

A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
System.InvalidOperationException: BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.
   at System.Net.Sockets.Socket.DoBeginConnect(EndPoint endPointSnapshot, SocketAddress socketAddress, LazyAsyncResult asyncResult)
   at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
   at InTheHand.Net.Bluetooth.Msft.SocketBluetoothClient.BeginConnect(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, Object state)
   at InTheHand.Net.Sockets.BluetoothClient.BeginConnect(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, Object state)
   at InTheHand.Net.Sockets.BluetoothClient.BeginConnect(BluetoothAddress address, Guid service, AsyncCallback requestCallback, Object state)
   at BTSyncClient.Form1.connect() in c:\users\----\documents\visual studio 2010\Projects\TestClient\TestClient\Form1.cs:line 154

I only know android application programming and i designed the C# by learning bit and pieces. FYI, My android phone is galaxy s with ICS running on it.Please point out my mistakes..

Source codes :

C# Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Windows.Forms;
using InTheHand.Net.Sockets;
using InTheHand.Net;
namespace BTSyncClient
{
    public partial class Form1 : Form
    {
        BluetoothClient myself;
        BluetoothDeviceInfo bTServerDevice;         
        private Guid uuid = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
        bool isConnected;
        public Form1()
        {
            InitializeComponent();              
            if (BluetoothRadio.IsSupported)
            {
                myself = new BluetoothClient();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }           
        private void button1_Click(object sender, EventArgs e)
        {
            connect();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                myself.GetStream().Close();
                myself.Dispose();
            }
            catch (Exception ex) { Console.Out.WriteLine(ex); }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
            DialogResult result = dialog.ShowDialog(this);
            if(result.Equals(DialogResult.OK)){
                bTServerDevice = dialog.SelectedDevice;                
            }
        }
        private void callback(IAsyncResult ar)
        {
            String msg = (String)ar.AsyncState;
            if (ar.IsCompleted)
            {
                isConnected = myself.Connected;
                if (myself.Connected)
                {
                    UTF8Encoding encoder = new UTF8Encoding();
                    NetworkStream stream = myself.GetStream();
                    if (!stream.CanWrite)
                    {
                        MessageBox.Show("Stream is not Writable");
                    }
                    System.IO.StreamWriter mywriter = new System.IO.StreamWriter(stream, Encoding.UTF8);
                    mywriter.WriteLine(msg);
                    mywriter.Flush();                    
                }
                else                    
                    MessageBox.Show("Damn thing isnt connected");

            }
        }
        private void connect()
        {
            try
            {
                if (bTServerDevice != null)
                {                    
                    myself.BeginConnect(bTServerDevice.DeviceAddress, uuid, new AsyncCallback(callback)
                    , message.Text);
                }
            }
            catch (Exception e) { Console.Out.WriteLine(e);  }
        }
    }
}

Server Thread

import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

public class ServerSocketThread extends Thread {
    private static final String TAG = "TestApp"; 
    private BluetoothAdapter btAdapter;
    private BluetoothServerSocket serverSocket;
    private boolean stopMe;
    private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    //private static final UUID uuid = UUID.fromString("6e58c9d5-b0b6-4009-ad9b-fd9481aef9b3");
    private static final String SERVICE_NAME = "TestService";
    public ServerSocketThread() {
        stopMe = false;
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        try {
            serverSocket = btAdapter.listenUsingRfcommWithServiceRecord(SERVICE_NAME, uuid);            
        } catch (IOException e) {
            Log.d(TAG,e.toString());
        }
    }
    public void signalStop(){
        stopMe = true;      
    }
    public void run(){
        Log.d(TAG,"In ServerThread");
        BluetoothSocket socket = null;
        while(!stopMe){
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {               
                break;
            }
            if(socket != null){             
                AcceptThread newClientConnection = new AcceptThread(socket);
                newClientConnection.start();
            }
        }
        Log.d(TAG,"Server Thread now dead");
    }

    // Will cancel the listening socket and cause the thread to finish
    public void cancel(){
        try {
            serverSocket.close();
        } catch (IOException e) {
        }
    }
}

Accept Thread

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

public class AcceptThread extends Thread {
    private BluetoothSocket socket;
    private String TAG = "TestApp";
    static int count = 0;
    public AcceptThread(BluetoothSocket Socket) {
        socket = Socket;
    }

    volatile boolean isError;
    String output;
    String error;

    public void run() {
        Log.d(TAG, "AcceptThread Started");
        isError = false;

        try {
            socket.connect();
        } catch (IOException e) {           
            Log.d(TAG,"Error while doing socket.connect()"+ ++count);
            Log.d(TAG, e.toString());
            Log.d(TAG,"Message: "+e.getLocalizedMessage());
            Log.d(TAG,"Localized Message: "+e.getMessage());
            isError = true;
        }
        InputStream in = null;
        try {
            in = socket.getInputStream();
        } catch (IOException e) {
            Log.d(TAG,"Error while doing socket.getInputStream()");
            Log.d(TAG, e.toString());
            Log.d(TAG,"Message: "+e.getLocalizedMessage());
            Log.d(TAG,"Localized Message: "+e.getMessage());
            isError = true;
        }
        Scanner istream = new Scanner(in);
        if (istream.hasNextLine()) {        
            Log.d(TAG, "Received : "+istream.nextLine());           
            Log.d(TAG,"Count of Thread is : " + count);
        }
        istream.close();
        try {
            in.close();
        } catch (IOException e) {
            Log.d(TAG,"Error while doing in.close()");
            Log.d(TAG, e.toString());
            Log.d(TAG,"Message: "+e.getLocalizedMessage());
            Log.d(TAG,"Localized Message: "+e.getMessage());
            isError = true;
        }
        try {
            socket.close();
        } catch (IOException e) {
            Log.d(TAG,"Error while doing socket.close()");
            Log.d(TAG, e.toString());
            Log.d(TAG,"Message: "+e.getLocalizedMessage());
            Log.d(TAG,"Localized Message: "+e.getMessage());
            isError = true;
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about android