首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >通过蓝牙将字符串从PC作为客户端发送到移动as服务器

通过蓝牙将字符串从PC作为客户端发送到移动as服务器
EN

Stack Overflow用户
提问于 2013-03-12 00:13:19
回答 2查看 68K关注 0票数 22

我需要通过蓝牙将字符串从PC传输到Android移动设备的帮助。Android移动设备应充当服务器,并在设备的屏幕上显示字符串消息。作为客户端的PC应将该字符串发送到移动设备。

我希望服务器对提取的字符串(通过蓝牙传输)做出反应。这意味着一方面服务器总是要监听新的字符串到达,但另一方面服务器仍然必须能够对这些消息做出反应(例如,从一个菜单导航到另一个菜单)。

我尝试使用BlueCove (2.1.1)作为BluetoothStack (我将BlueCove中的jar作为库添加到两个项目中),并结合我发现的here的服务器-客户端通信示例。

更新:

多亏了user_CC对服务器使用RFComm连接,更新了服务器上的代码:

代码语言:javascript
复制
public class RFCommServer extends Thread{

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;

private Activity activity;

public RFCommServer(Activity activity) {
    this.activity = activity;
}

public void run() {
    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();        

    // Listen to the server socket if we're not connected
    while (true) {

        try {
            // Create a new listening server socket
            Log.d(this.getName(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService", MY_UUID);
            //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        try {
            Log.d(this.getName(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);

            // here you can use the Input Stream to take the string from the client whoever is connecting
            //similarly use the output stream to send the data to the client

            RelativeLayout layout = (RelativeLayout) activity.findViewById(R.id.relativeLayout_Layout);
            TextView text = (TextView) layout.findViewById(R.id.textView_Text);

            text.setText(mmInStream.toString());
        } catch (Exception e) {
            //catch your exception here
        }
    }
}

来自here的SPP客户端代码

代码语言:javascript
复制
/**
* A simple SPP client that connects with an SPP server
*/
public class SampleSPPClient implements DiscoveryListener{

//object used for waiting
private static Object lock=new Object();

//vector containing the devices discovered
private static Vector vecDevices=new Vector();

private static String connectionURL=null;

public static void main(String[] args) throws IOException {

    SampleSPPClient client=new SampleSPPClient();

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: "+localDevice.getBluetoothAddress());
    System.out.println("Name: "+localDevice.getFriendlyName());

    //find devices
    DiscoveryAgent agent = localDevice.getDiscoveryAgent();

    System.out.println("Starting device inquiry...");
    agent.startInquiry(DiscoveryAgent.GIAC, client);

    try {
        synchronized(lock){
            lock.wait();
        }
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }


    System.out.println("Device Inquiry Completed. ");

    //print all devices in vecDevices
    int deviceCount=vecDevices.size();

    if(deviceCount <= 0){
        System.out.println("No Devices Found .");
        System.exit(0);
    }
    else{
        //print bluetooth device addresses and names in the format [ No. address (name) ]
        System.out.println("Bluetooth Devices: ");
        for (int i = 0; i <deviceCount; i++) {
            RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
            System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
        }
    }

    System.out.print("Choose Device index: ");
    BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

    String chosenIndex=bReader.readLine();
    int index=Integer.parseInt(chosenIndex.trim());

    //check for spp service
    RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1);
    UUID[] uuidSet = new UUID[1];
    uuidSet[0]=new UUID("446118f08b1e11e29e960800200c9a66", false);

    System.out.println("\nSearching for service...");
    agent.searchServices(null,uuidSet,remoteDevice,client);

    try {
        synchronized(lock){
            lock.wait();
        }
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }

    if(connectionURL==null){
        System.out.println("Device does not support Simple SPP Service.");
        System.exit(0);
    }

    //connect to the server and send a line of text
    StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL);

    //send string
    OutputStream outStream=streamConnection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Test String from SPP Client\r\n");
    pWriter.flush();


    //read response
    InputStream inStream=streamConnection.openInputStream();
    BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader2.readLine();
    System.out.println(lineRead);


}//main

//methods of DiscoveryListener
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
    //add the device to the vector
    if(!vecDevices.contains(btDevice)){
        vecDevices.addElement(btDevice);
    }
}

//implement this method since services are not being discovered
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
    if(servRecord!=null && servRecord.length>0){
        connectionURL=servRecord[0].getConnectionURL(0,false);
    }
    synchronized(lock){
        lock.notify();
    }
}

//implement this method since services are not being discovered
public void serviceSearchCompleted(int transID, int respCode) {
    synchronized(lock){
        lock.notify();
    }
}


public void inquiryCompleted(int discType) {
    synchronized(lock){
        lock.notify();
    }

}//end method

}

为了进行测试,我使用带有最新Android API的Galaxy Nexus (GT-I9250)。

多亏了user_CC,客户端和服务器现在可以无异常地运行了。但遗憾的是,客户端无法连接到服务器(参见下面的屏幕截图)。这是因为从来没有设置过connectionURL (因此默认情况下它会跳到这里的if(connectionURL==null)中)。

如何更改客户端代码,以便真正将其与服务器连接?在下面的代码行中,我需要一个合适的connectionURL

代码语言:javascript
复制
StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL)

到目前为止,我只发现我需要以某种方式获取ServiceRecord,遗憾的是,here的示例代码中也没有描述这一点。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-12 00:41:39

我还发表了一些评论,以供您理解。

代码语言:javascript
复制
    private class AcceptThread extends Thread {
    // The local server socket
    private BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
    }

    public void run() {         
        BluetoothSocket socket = null;

                    BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();

        // Listen to the server socket if we're not connected
        while (true) {

            try {
                // Create a new listening server socket
                Log.d(TAG, ".....Initializing RFCOMM SERVER....");

                // MY_UUID is the UUID you want to use for communication
                mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);                    
                //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);  you can also try using In Secure connection...

                // This is a blocking call and will only return on a
                // successful connection or an exception                    
                socket = mmServerSocket.accept();                   

            } catch (Exception e) {

            }

            try {
                Log.d(TAG, "Closing Server Socket.....";                    
                mmServerSocket.close();



                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the BluetoothSocket input and output streams

                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();


                mmInStream = new DataInputStream(tmpIn);
                mmOutStream = new DataOutputStream(tmpOut); 

                // here you can use the Input Stream to take the string from the client whoever is connecting
                //similarly use the output stream to send the data to the client
            } catch (Exception e) {
                //catch your exception here
            }

        }
    }

}

我希望这能帮到你

关于你的另一个问题:

在客户端(PC)上声明javax.bluetooth.UUID的UUID类应该来自javax.bluetooth.UUID

代码语言:javascript
复制
   uuidSet2[0] = new UUID("446118f08b1e11e29e960800200c9a66", false);

在服务器端声明java.util.UUID (安卓)

代码语言:javascript
复制
    UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");
票数 8
EN

Stack Overflow用户

发布于 2013-03-12 00:24:47

我不是Java开发人员,但我在Mono for Android (c#)上遇到过类似的问题

SPP的UUID应为"00001101-0000-1000-8000-00805F9B34FB"

这是用于标识蓝牙SPP适配器的已知UID。

在我的c#代码中,看起来像

代码语言:javascript
复制
private static UUID MY_UUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");

我猜您可以将您的Java代码更新为如下所示:

代码语言:javascript
复制
new UUID("00001101-0000-1000-8000-00805F9B34FB", true);

虽然我不确定这个函数接受什么参数,所以你可能需要检查一下。

我使用安卓设备作为客户端,但这些信息可能对你有用,

所以我将在这里包含我的c#代码,它最初是从Java示例中翻译过来的,

所以你应该能够把它翻译回来:

代码语言:javascript
复制
btAdapter = BluetoothAdapter.DefaultAdapter;

btAdapter.CancelDiscovery(); //Always call CancelDiscovery before doing anything
remoteDevice = btAdapter.GetRemoteDevice(Settings["deviceaddress"].ToString());

socket = remoteDevice.CreateRfcommSocketToServiceRecord(MY_UUID);
socket.Connect();

基本上,我获取默认适配器,取消所有正在运行的发现操作,然后创建到另一个设备的套接字。在您的情况下,您将希望倾听而不是连接,但仅供参考。

我希望这对你有所帮助,很抱歉我不能给你更多的Java相关信息。

“更新:”我在Java中找到了一个小示例,它的方法与我使用的方法基本相同:Problems with connecting bluetooth SPP in android?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15343369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档