Java 使用蓝牙加密狗将字符串从PC发送到android应用程序
我正在关注这个GitHub项目 PC作为客户端工作,android应用作为服务器工作。服务器搜索设备并向名为BT_的设备发送字符串。而android设备侦听连接并接收字符串 问题是它不一致。有时它正确发送字符串,但有时PC客户端代码保持运行,但无法发送字符串。大多数情况下,它无法调用broadcastCommand函数。它会在此处死机。 它第一次总是工作正常。但是它不再工作了,过了一段时间它又开始工作了。当我每次关闭android应用程序并再次打开它时,它会正常接收。 请帮忙! PC客户端代码为: 公共类BT_虚拟扩展线程实现DiscoveryListener{Java 使用蓝牙加密狗将字符串从PC发送到android应用程序,java,android,multithreading,sockets,bluetooth,Java,Android,Multithreading,Sockets,Bluetooth,我正在关注这个GitHub项目 PC作为客户端工作,android应用作为服务器工作。服务器搜索设备并向名为BT_的设备发送字符串。而android设备侦听连接并接收字符串 问题是它不一致。有时它正确发送字符串,但有时PC客户端代码保持运行,但无法发送字符串。大多数情况下,它无法调用broadcastCommand函数。它会在此处死机。 它第一次总是工作正常。但是它不再工作了,过了一段时间它又开始工作了。当我每次关闭android应用程序并再次打开它时,它会正常接收。 请帮忙! PC客户端代码为
/**
* Service serial-port UUID
*/
protected UUID defaultUUID = new UUID(0x1101);
/**
* Local bluetooth device.
*/
private LocalDevice local;
/**
* Agent responsible for the discovery of bluetooth devices.
*/
private DiscoveryAgent agent;
/**
* Output stream used to send information to the bluetooth.
*/
private DataOutputStream dout;
/**
* Bluetooth Connection.
*/
private StreamConnection conn;
/**
* List of bluetooth devices of interest. (name starting with the defined token)
*/
private Vector<RemoteDevice> devices;
/**
* Services of interest (defined in UUID) of each device.
*/
private Vector<ServiceRecord> services;
public BT_Dummy() {
services = new Vector<ServiceRecord>();
}
@Override
public void run() {
findDevices();
}
/**
* Find all the discoverable devices in range.
*/
protected void findDevices(){
try{
devices = new Vector<RemoteDevice>();
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, this);
debugString("Starting device discovery...");
}catch(Exception e) {
debugString("Error initiating discovery.");
}
}
/**
* Obtains a list of services with the UUID defined from a device.
*
* @param device
* Device to obtain the service list.
*/
protected void findServices(RemoteDevice device){
try{
UUID[] uuids = new UUID[1];
uuids[0] = defaultUUID; //The UUID of the each service
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
agent.searchServices(null, uuids, device, this);
debugString("Starting Service Discovery...");
}catch(Exception e){
debugString("Error finding services.");
}
}
/**
* Sends a message to all the devices. (using the service)
*
* @param str
* Byte array which represents a string.
*/
public void broadcastCommand(String str) {
for(ServiceRecord sr : services) {
String url = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
conn = null;
try {
debugString("Sending command to " + url);
conn = (StreamConnection) Connector.open(url);
dout = new DataOutputStream(conn.openOutputStream());
dout.writeUTF(str);
debugString(String.format("Sending %s", str));
dout.flush();
dout.close();
conn.close();
debugString("Sent. Connection Closed.");
} catch (Exception e) {
debugString("Failed to connect to " + url);
e.printStackTrace();
}
}
}
@Override
public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1) {
try {
String name = arg0.getFriendlyName(true);
debugString("Found device: " + name);
if(name.startsWith("BT_")) {
devices.add(arg0);
}
} catch (IOException e) {
debugString("Failed to get remoteDevice Name.");
}
}
@Override
public void inquiryCompleted(int arg0) {
debugString("Inquiry Completed.");
// Start service probing
for(RemoteDevice d :devices) {
findServices(d);
}
}
@Override
public void serviceSearchCompleted(int arg0, int arg1) {
debugString("Service search completed.");
broadcastCommand(new String("Hello world!"));
}
@Override
public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
for(ServiceRecord x : arg1) {
services.add(x);
}
}
/**
* Helper to format a debug string for output.
*
* @param str
* Debug Message
*/
protected static void debugString(String str) {
System.out.println(String.format("%s :: %s", BT_Dummy.class.getName(), str));
}
}
我已经使用android源代码示例完成了这一点: 对于PC代码,我使用了一个简单的python服务器:
#!/usr/bin/python
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",6))
#server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "8ce255c0-200a-11e0-ac64-0800200c9a66" #Insecure
#uuid = "fa87c0d0-afac-11de-8a39-0800200c9a66"
advertise_service( server_sock, "BluetoothChatInsecure",
service_id = uuid,
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"
确保android应用程序中的UUID与PC服务器中的UUID匹配
RFCOMM并不是最新的数据交换方式,GATT是一个更高级的系统,它也受iOS支持。另一方面,RFCOMM更容易启动,它受Android、Windows和BlueZ堆栈的支持。它的客户端将在PC上运行在哪里?如果我看得对,那就是用python编写的PC脚本。客户端是android应用程序,服务器是一个运行在PC上的python脚本。android应用程序也可以配置为服务器。我没有一个用于客户端的PC示例。
#!/usr/bin/python
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",6))
#server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "8ce255c0-200a-11e0-ac64-0800200c9a66" #Insecure
#uuid = "fa87c0d0-afac-11de-8a39-0800200c9a66"
advertise_service( server_sock, "BluetoothChatInsecure",
service_id = uuid,
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"