通过蓝牙将字符串从PC作为客户端发送到移动设备作为服务器 [英] Sending a string via bluetooth from a PC as client to a mobile as server

查看:354
本文介绍了通过蓝牙将字符串从PC作为客户端发送到移动设备作为服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是蓝牙新手,真的需要你的帮助。我已经困扰了这个问题了几天,搜索互联网和stackoverflow,但不能真正找到我正在寻找。

I'm a Bluetooth Newbie and really need your help. I've been stucked with this question for some days now and searching the internet and stackoverflow, but can't really find what I'm looking for.

我需要帮助通过将字符串从pc传输到android移动设备。 Android移动设备应该充当服务器并且在设备的屏幕上显示字符串消息。

I need help by transfering a string from a pc to an android mobile device. The android mobile device should act as a server and displays the string message on the screen of the device. The PC which is the client should send the string to the mobile device.

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

I want the server react on the extracted string (transfered via Bluetooth). That means that on one side the server always has to listen for new strings to arrive, but on the other side still has to be able to react on these messages (e.g. navigate from one menu to another).

我尝试使用BlueCove(2.1.1)作为BluetoothStack(为此,我将从bluecove的jar作为库添加到两个项目)结合一个服务器 - 客户端通信的示例发现于:
http:// www。 jsr82.com/jsr-82-sample-spp-server-and-client/

I tried it by using BlueCove (2.1.1) as BluetoothStack (for which I add the jar from bluecove as a library to both projects) in combination with an example for a server-client communication that i found in: http://www.jsr82.com/jsr-82-sample-spp-server-and-client/

由于user_CC使用RFComm连接为服务器更新了代码服务器

Updated code from server thanks to user_CC using a RFComm connection for the server

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
        }
    }
}

SPP客户端的代码来自 http://www.jsr82.com/jsr-82-sample-spp-server-and-client/

Code of the SPP Client from http://www.jsr82.com/jsr-82-sample-spp-server-and-client/

/**
* 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

}


b $ b

对于测试,我使用Galaxy Nexus(GT-I9250)与最新的Android API。

For testing I use a Galaxy Nexus (GT-I9250) with the lastest Android API.

由于user_CC,客户端和服务器现在运行异常。但可惜的是客户端不能连接到服务器(见截图)。这是因为connectionURL从未设置(因此它在这里跳入if(connectionURL == null)默认情况下,如何更改客户端代码,以便我实际上可以连接到服务器。我需要一个正确的connectionURL在下面这行:StreamConnection streamConnection =(StreamConnection)Connector.open(connectionURL);到目前为止,我只发现我不知何故需要得到ServiceRecord,可悲的是这也没有在示例代码中描述从 http://www.jsr82.com/jsr-

Thanks to user_CC, the client and server now runs without an exception. But sadly the client is not able to connect to the server (see the screenshot). It is because the connectionURL is never set (thus it jumps in here "if(connectionURL==null)" by default, how can I change the client code, so that I actually can connect it with the server. I need a proper connectionURL in the following line: StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL); So far I only found out that I somehow need to get the ServiceRecord, sadly this is also not described in the example code from http://www.jsr82.com/jsr-82-sample-spp-server-and-client/

任何人都可以帮助我解决这个问题,或者为我提供一个工作示例从PC(作为客户端)到Android移动设备(作为服务器))。您的帮助非常感谢!

Can anyone help me in solving this problem, or providing me with an working example for the problem (of transfering a string from a pc (as client) to a android mobile device (as server)). Your help is very appreciated!

推荐答案

将需要使用RFComm APIS进行通信工作,我已经管理定义一个类,它是一个Thread,并将作为一个服务器,并监听客户端连接。我也给了一些意见,让你理解。

You will need to use the RFComm APIS to make the communication work I have managed to define a class which is a Thread and will be acting as a server and listening for client connections. I have also placed some comments for you to understand.

    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
            }

        }
    }

}



我希望这有助于

I hope this helps

对于你的另一个问题:

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

Declaring javax.bluetooth.UUID on Client side (PC) UUID class should be from javax.bluetooth.UUID

   uuidSet2[0] = new UUID("446118f08b1e11e29e960800200c9a66", false);

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

Declaring java.util.UUID at Server Side (Android)

    UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

这篇关于通过蓝牙将字符串从PC作为客户端发送到移动设备作为服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆