⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spp_client.java

📁 benhui网的蓝牙例子
💻 JAVA
字号:
package net.benhui.btgallery.spp_bt;

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

import net.benhui.btgallery.spp_gui.*;

/**
 *
 * <p>Title: Example Serial Port Profile Client</p>
 * Description: Important area: send_SPP_message()
 * This client only does the portion that send and receive data over a SPP
 * connection. In an actual client applicaion, you also need to do device
 * discovery and service discovery. This is taken care by Bluelet.
 * @author Ben Hui (www.benhui.net)
 * @version 1.0
 *
 * LICENSE:
 * This code is licensed under GPL. (See http://www.gnu.org/copyleft/gpl.html)
 */

public class SPP_Client
{

  public SPP_Client()
  {
  }


  /**
   * Send a message to server using Serial Port Profile.
   * Connect to incoming service record, send a text, and read
   * in a text. This method illustrate how to send and receive
   * data using serial port profile.
   * Device and service discovery is part of Serial Port client but it is
   * done by Bluelet component. See SPP_MIDlet for usage of Bluelet.
   * @param msg
   */
  public void send_SPP_message(ServiceRecord r, String msg)
  {
    log( "send_SPP2");
    // obtain the URL reference to this service on remote device
    String url  = r.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false );
    log("url:"+url);

    try
    {
      // obtain connection and stream to this service
      StreamConnection con = (StreamConnection) Connector.open( url );
      log("connected to server. now writing '"+msg+"'");


      DataOutputStream out = con.openDataOutputStream();

      // write data into serial stream
      out.writeUTF( msg );
      out.flush();
      log("write and flush ok");

      // this wait is artificial, the purpose to do wait until the
      // server side really receive the message before we close the connection
      // in theory, this is not necessary, but when I use the Rococo simulator,
      // sometimes the connection dropped on the server side when I close it here
      // it may be a bug in Rococo simulator.
      Thread.sleep(1000);

      // finish, close output stream
      out.close();

      // now the server should have echo back the string, so we read it
      // using input stream
      DataInputStream in = con.openDataInputStream();
      String s = in.readUTF();

      log("read in data '"+s+"'");

      con.close();

    } catch (Exception e)
    {
      e.printStackTrace();
      SPP_MIDlet.alert( e, SPP_MIDlet.instance.spp_screen );
    }

  }

  public void log( String s )
  {
    SPP_MIDlet.log( s );
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -