简体   繁体   English

通过蓝牙从Java Server发送文本到Android客户端

[英]Send text through Bluetooth from Java Server to Android Client

First of all... don't redirect me to Bluetooth Chat and I have fully read it. 首先......不要将我重定向到蓝牙聊天,我已经完全阅读了它。

I have an Android Client which stablishes the connection properly with the server, and what's most I can send text to the server in my pc and show it correctly, but I can't do the opposite action, send a simple string from the server to the client and show it in my android app. 我有一个Android客户端,它可以正确地与服务器建立连接,我可以将最多的文本发送到我的电脑中的服务器并正确显示,但我不能做相反的操作,从服务器发送一个简单的字符串客户端并在我的Android应用程序中显示它。

I don't want to implement a chat is just to show how BT communication works between a Java Server and Android Client. 我不想实现聊天只是为了展示如何在Java服务器和Android客户端之间进行BT通信。

To make it easy: 为了方便起见:

I send the text at the end of the startServer() method in the server class. 我在服务器类的startServer()方法的末尾发送文本。

I try to read the text from the server at the beginning of onPause(). 我尝试在onPause()开头从服务器读取文本。

** **

[Solved] Solution Below [解决]解决方案如下

**. **。

The code is as follows: 代码如下:

Android BT Client: Android BT客户端:

/*...libraries here...*/
  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:10:60:AA:B9:B2";

  /** Called when the activity is first created. */
  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();
  }

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

  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.
    try {
      btSocket.connect();
      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...");
    String message = "Hello from Android.\n";
    out.append("\n\n...The message that we will send to the server is: "+message);

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

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

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

    //out.append("\n...Hello\n");
    InputStream inStream;
    try {
        inStream = btSocket.getInputStream();
        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader.readLine();
        out.append("\n..."+lineRead+"\n");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    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() + ".");
    }
  }

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

  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();
  }
}

and the Java BT Server: 和Java BT服务器:

    import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.bluetooth.*;
import javax.microedition.io.*;

/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {

    //start server
    private void startServer() throws IOException{

        //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the servicve url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

        //Wait for client connection
        System.out.println("\nServer Started. Waiting for clients to connect...");
        StreamConnection connection=streamConnNotifier.acceptAndOpen();

        RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
        System.out.println("Remote device name: "+dev.getFriendlyName(true));

        //read string from spp client
        InputStream inStream=connection.openInputStream();
        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader.readLine();
        System.out.println(lineRead);

        //send response to spp client
        OutputStream outStream=connection.openOutputStream();
        BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(outStream));
        bWriter.write("Response String from SPP Server\r\n");

        /*PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
        pWriter.write("Response String from SPP Server\r\n");
        pWriter.flush();
        pWriter.close();*/

        streamConnNotifier.close();

    }


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

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

        SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
        sampleSPPServer.startServer();

    }
}

Solution : It's just a small change in the server side. 解决方案 :这只是服务器端的一个小变化。 I don't know why but instead of using BufferedWrite to write in the socket, we need to use PrinterWriter to do so. 我不知道为什么,但我们需要使用PrinterWriter来代替使用BufferedWrite在套接字中写入。 I add that piece of code modified: 我添加了一段修改过的代码:

BT Server: BT服务器:

    ....
    //read string from spp client
    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();
    System.out.println(lineRead);

    //send response to spp client
    OutputStream outStream=connection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Response String from SPP Server\r\n");
    pWriter.flush();

    pWriter.close();

    streamConnNotifier.close();
    ...

It looks like your BufferedWriter cache was not being flushed, the data was simply remaining in the buffer without being sent. 看起来你的BufferedWriter缓存没有被刷新,数据只是保留在缓冲区而不被发送。 Calling bWriter.flush() after your bWriter.write() should fix the issue and cause the data to be flushed to the output stream. 调用bWriter.flush()的后bWriter.write()应该解决的问题,并会导致数据被刷新到输出流。 You can also consider changing your code to follow this: 您还可以考虑更改代码以遵循以下步骤:

PrintWriter pWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream)));

This will cause the PrintWriter output to be buffered, instead of being written immediately to the output stream, which can be inefficient. 这将导致PrintWriter输出被缓冲,而不是立即写入输出流,这可能是低效的。

For your purposes though, omitting the BufferedWriter should be fine, as you will most likely want an immediate flush to the output stream (which PrintWriter does). 但是,出于您的目的,省略BufferedWriter应该没问题,因为您很可能希望立即刷新输出流(PrintWriter会这样做)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过蓝牙将字符串从Java Server发送到Android客户端 - Send String through Bluetooth From Java Server to Android Client 无法通过文本字段将消息从服​​务器发送到android中的客户端 - Unable to send message from server to the client in android through text field 将Bluetooth Android客户端连接到Bluetooth Java Server - Connect Bluetooth Android Client to Bluetooth Java Server java蓝牙服务器将消息发送回客户端 - java bluetooth server send message back to client 如何通过Java套接字从客户端向服务器发送多个映像? - How to send multiple Images from client to server through java sockets? 通过 Socket Outputstream 从 Swift 客户端向 Java 服务器发送消息 - Send message through Socket Outputstream from Swift Client to Java Server 通过单击按钮将文本消息从 java 服务器发送到 android 客户端使用套接字 - send text message from java server to android client usig sockets by clicking on a button 是否可以通过inputstream-outputstream在Android蓝牙中将数据从客户端发送到服务器? - Is it possible to send data from client to server in Android bluetooth via inputstream-outputstream? 使用套接字将服务器JAVA的图像发送到android客户端 - send image from server JAVA to android client using socket 如何将JsonArray从客户端(java或Android)发送到servlet(服务器) - How to Send JsonArray From Client(java or Android ) To servlet(Server)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM