この場合、Android アプリケーションはサーバーとして機能します。serverSocket を処理するスレッドと、ソケット接続を処理する別のスレッドを作成するメイン アクティビティがあります。C# と android に共通の uuid を使用しています。
C# 用の 32feet bluetooth ライブラリを使用しています。
私が直面しているエラーは
1)私のlogcatはこのデバッグログを示しています
socket.connect()1
java.io.IOException: 不正な状態の
ファイル記述子メッセージ: 不正な状態の
ファイル記述子ローカライズされたメッセージ:不正な状態のファイル記述子
受信: スレッドのテスト接続
カウント: 1
2) 2 回目に C# アプリ経由で何かを送信すると、次の例外がスローされます。
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
私は Android アプリケーションのプログラミングしか知らないので、少しずつ学習して C# アプリを設計しました。参考までに、私の Android フォンは ICS が実行されている Galaxy S です。私の間違いを指摘してください..
ソースコード:
C# コード
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); }
}
}
}
サーバースレッド
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) {
}
}
}
スレッドを受け入れる
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;
}
}
}