1

我正在尝试在 C# 中开发一个应用程序,它充当 Android 手机的服务器。我在 C# 中将 32feet.net 用于蓝牙,我有一个在 android 中运行的服务器,它只是向服务器发送一个套接字。在 pc 中运行的服务器需要监听连接并显示连接状态。所有这些都是我项目的基础。服务器代码如图所示:

namespace testserver
{
class Program
{

    static void Main(string[] args)
    {

        BluetoothClient bc = new BluetoothClient();
        BluetoothDeviceInfo[] dev;
        BluetoothDeviceInfo td=null;
        Guid id = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");
      //  Console.WriteLine(id.ToString());
       // Console.Read();
        dev = bc.DiscoverDevices();
        foreach (BluetoothDeviceInfo d in dev)
        {
            if (d.DeviceName == "ST21i")//my phone name
            {
                td=d;
                break;
            }
        }
        try
        {

            BluetoothAddress addr = td.DeviceAddress;
            BluetoothListener bl = new BluetoothListener(addr, id);
            bl.Start();
            if (bl.AcceptSocket() != null)
                Console.WriteLine("Success");
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception : "+e.Message);
            Console.Read();
        }


    }
}

}

这是我的安卓代码:

public class MainActivity extends Activity {


 BluetoothAdapter adapter;
     BluetoothDevice bd;
BluetoothSocket sock;
OutputStream ostr;
int REQUEST_ENABLE_BT;
String str="5C:AC:4C:DD:CC:0D";

private static final UUID id=UUID.fromString("00112233-4455-6677-8899-         aabbccddeeff");
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    adapter=BluetoothAdapter.getDefaultAdapter();

   if (!adapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }


    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
 Toast.makeText(getApplicationContext(), "clicked button",            Toast.LENGTH_LONG).show();
    try
    { 
        bd=adapter.getRemoteDevice(str);                      Toast.makeText(getApplicationContext(),"Server is    running at   "+bd.getName().toString()+"...", Toast.LENGTH_LONG).show();
                   sock=bd.createInsecureRfcommSocketToServiceRecord(id);                    sock.connect();
                ostr=sock.getOutputStream();
                ostr.write(0);
            }
            catch(Exception e)
            {
                 Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });

}

}

我的问题是:

1)在 pc 中我遇到异常,请求的地址在其上下文中无效(因此服务器无法运行) 2)在电话中,服务发现失败(因为服务器不可用)

如何更正服务器并运行程序?

4

1 回答 1

1

我将蓝牙监听器对象的创建从 BluetoothListener bl = new BluetoothListener(addr, id);更改为 BluetoothListener bl = new BluetoothListener(id);,一切正常..

于 2013-02-17T06:20:03.727 回答