[英]Sending data from Android (Client) to Python (Server) over Bluetooth
I am trying to send data from Android Client (Nexus 4) to Python Server (Linux Machine) over Bluetooth using Python-bluez. 我正在尝试使用Python-bluez将数据从Android客户端(Nexus 4)通过蓝牙发送到Python服务器(Linux计算机)。 Whenever the client writes some bytes to the OutputStream it throws an IO exception "Broken Pipe".
每当客户端将一些字节写入OutputStream时,它将抛出IO异常“ Broken Pipe”。 The server also seems that it does not accept any connections although the Android client did not throw any exceptions after "socket_name.connect()"
服务器似乎也不接受任何连接,尽管Android客户端在“ socket_name.connect()”之后未引发任何异常。
Android Client: Android客户端:
public class MainActivity extends Activity {
private BluetoothSocket ClientSocket;
private BluetoothDevice Client;
private ConnectedThread Writer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public BluetoothAdapter mblue;
public void connect(View sender)
{
mblue = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = 1;
final TextView er = (TextView)findViewById(R.id.Error);
if(mblue == null)
er.setText("No Bluetooth!");
else if (mblue.isEnabled()) {
er.setText(mblue.getAddress() + " " + mblue.getName());
}
else{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void disov(View sender)
{
final TextView er = (TextView)findViewById(R.id.Error);
boolean tr = mblue.startDiscovery();
if(tr == true)
{
er.setText("Disovering !!");
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
public void start(View sender)
{
final TextView er = (TextView)findViewById(R.id.Error);
final TextView lol = (TextView)findViewById(R.id.editText1);
Writer.write(lol.getText().toString().getBytes());
lol.setText("");
}
public void send(View sender)
{
ConnectThread con = new ConnectThread(Client);
con.start();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
//mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
final TextView er = (TextView)findViewById(R.id.Error);
if(device.getAddress().equals("9C:2A:70:49:61:B0") == true)
{
Client = device;
er.setText("Connected with the target device!");
}
}
}
};
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
UUID myuuid = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
final TextView er = (TextView)findViewById(R.id.Error);
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(myuuid);
} catch (IOException e) {}
ClientSocket = mmSocket = tmp;
Writer = new ConnectedThread(ClientSocket);
}
public void run() {
// Cancel discovery because it will slow down the connection
mblue.cancelDiscovery();
final TextView er = (TextView)findViewById(R.id.Error);
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {}
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {}
}
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
final TextView er = (TextView)findViewById(R.id.Error);
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {}
mmInStream = tmpIn;
mmOutStream = tmpOut;
er.setText(er.getText() + "\n" + socket.toString());
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
// .sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
final TextView er = (TextView)findViewById(R.id.Error);
try {
mmOutStream.write(bytes);
//mmOutStream.
} catch (IOException e)
{
er.setText(e.toString());
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Python Server: Python服务器:
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
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")
Any help is appreciated. 任何帮助表示赞赏。
You have used two public classes ie public class MainActivity extends Activity{}
and public class ConnectedThread extends Thread {}
. 您使用了两个公共类,即
public class MainActivity extends Activity{}
和public class ConnectedThread extends Thread {}
。 But in Java there should be one public class and any number of other classes in one JavaClass file. 但是在Java中,一个JavaClass文件中应该有一个公共类,而其他任何类也应有。 So remove
public class ConnectedThread extends Thread {}
from that file and create a new Java class: public class ConnectedThread extends Thread {}
in the same package. 因此,从该文件中删除
public class ConnectedThread extends Thread {}
并创建一个新的Java类: public class ConnectedThread extends Thread {}
在同一包中public class ConnectedThread extends Thread {}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.