Android的蓝牙客户端和服务器将无法连接 [英] Android Bluetooth Client and Server Won't Connect

查看:198
本文介绍了Android的蓝牙客户端和服务器将无法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在试图创建一个谷歌眼镜(客户端)连接到我的计算机(服务器的Python)的应用程序。我想送简单的字符串。我已经尝试了多种方法,但还没有多少运气。我目前使用的一些示例code,我发现。无论运行后,我得到的消息

I am currently trying to create an app that connects Google Glass(client) to my computer(python server). I would like to send simple strings. I have tried multiple ways but haven't had much luck. I am currently using some sample code I found. After running both, i get the message

在onResume()和写入过程中发生了异常:套接字关闭

"In onResume() and an exception occurred during write: Socket Closed"

在玻璃上,和我的电脑(惠普Pavilion DV6运行Ubuntu 12.04与蓝牙适配器)完全冻结。有一次GUI本身死机了,我一直在寻找在控制台上的堆栈跟踪(即吓人黑屏)。

on Glass, and my computer(HP Pavillion Dv6 running Ubuntu 12.04 with Bluetooth Dongle) completely freezes. One time the GUI itself crashed and I was looking at a stack trace on the console(that scary black screen).

下面是客户端code:

Here is the client code:

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import com.myPackage.glassbluetooth.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class ConnectTest extends Activity {
    TextView out;
    private static final int REQUEST_ENABLE_BT = 1;
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;

    // Well known SPP UUID
    private static final UUID MY_UUID =
            UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Insert your server's MAC address
    private static String address = "00:1F:81:00:08:30";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        out = (TextView) findViewById(R.id.out);

        out.append("\n...In onCreate()...");

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        CheckBTState();
    }

    @Override
    public void onStart() {
        super.onStart();
        out.append("\n...In onStart()...");
    }

    @Override
    public void onResume() {
        super.onResume();

        out.append("\n...In onResume...\n...Attempting client connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d("CONNECTTEST", "Try to open socket");

        try {
            btSocket.connect();
            Log.d("CONNECTTEST", "btSocket.connect executed");
            out.append("\n...Connection established and data link opened...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        out.append("\n...Sending message to server...");

        try {
            outStream = btSocket.getOutputStream();
        } catch (IOException e) {
            AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
        }

        String message = "Hello from Android.\n";
        byte[] msgBuffer = message.getBytes();
        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
            if (address.equals("00:00:00:00:00:00")) 
                msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
            msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

            AlertBox("Fatal Error", msg);       
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        out.append("\n...In onPause()...");

        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
            }
        }

        try     {
            btSocket.close();
        } catch (IOException e2) {
            AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        out.append("\n...In onStop()...");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        out.append("\n...In onDestroy()...");
    }

    private void CheckBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on

        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) { 
            AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
        } else {
            if (btAdapter.isEnabled()) {
                out.append("\n...Bluetooth is enabled...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    public void AlertBox( String title, String message ){
        new AlertDialog.Builder(this)
        .setTitle( title )
        .setMessage( message + " Press OK to exit." )
        .setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                finish();
            }
        }).show();
    }
}

和这里是服务器code:

and here is the server code:

from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "1aefbf9b-ea60-47de-b5a0-ed0e3a36d9a5"
testUuid = "00001101-0000-1000-8000-00805F9B34FB"

advertise_service( server_sock, "GlassServer",
                   service_id = testUuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ], 
#                   protocols = [ OBEX_UUID ] 
                    )

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")

下面是hcitool的输出:

Here is the output of hcitool:

$ hcitool scan
Scanning ...
    F4:B7:E2:F9:74:63   GLASS-YUKON
$ hcitool dev
Devices:
    hci0    00:1F:81:00:08:30

没有人有任何想法怎么回事?另外,如果你知道任何有关样本程序的可能的工作,我会兴趣尝试他们!在此先感谢!

Does anyone have any idea whats going on? Also, if you know of any relevant sample programs that might work I would be interested in trying them! Thanks in advance!

凹凸,任何人都可以在这方面帮助?

Bump, can anyone help with this?

与具有内置蓝牙功能的电脑试验后,我能磨练的问题多一点。当code尝试创建RFCOMM插座出现问题。使用code现在我有,我得到一个异常服务发现失败。我被用在这里找到了意见后摆脱错误的:<一href=\"http://stackoverflow.com/questions/3397071/service-discovery-failed-exception-using-bluetooth-on-android\">Service发现在Android

After experimenting with a computer which had bluetooth capabilities built in, I was able to hone in on the problem a little more. The problem occurs when the code attempts to create the RFComm socket. Using the code I have now, I get an exception Service Discovery failed. I got rid of that error after using the advice found here: Service discovery failed exception using Bluetooth on Android

但现在我得到,说:主机已关闭异常。该修复程序都不我找到的工作。任何想法?

but now I get an exception that says "Host is down". None of the fixes I found worked. Any ideas?

推荐答案

我可以回答我的问题的一部分:

I can answer one part of my question:

内核恐慌不是由于我的code,但对我的蓝牙适配器,而问题的驱动程序软件。我想这本身有蓝牙功能的计算机上code和我SANS内核恐慌相同的结果。

The kernel panic is not due to my code but rather faulty driver software for my Bluetooth Dongle. I tried the code on a computer which natively had Bluetooth capabilities and I got the same results sans the kernel panic.

这篇关于Android的蓝牙客户端和服务器将无法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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