BluetoothServerSocket详解

一. BluetoorhServerSocket简介


1. 继承关系


public final class BluetoothServerSocket extends Object implements Closeable

继承了Object类, 实现了Closeable接口;

Closeable是可以关闭的数据源或者目标, 实现该接口必须重写close()方法, 调用close()方法可以释放该对象保存的资源;


2. 该类简介


使用BluetoothServerSocket可以创建一个监听服务端口, 使用accept()方法阻塞, 当该方法监测到连接的时候, 就会返回一个BluetoothSocket对象来管理这个连接, 例如获取输入输出流等; 


RFCOMM端口是最常用的蓝牙端口, 该端口是面向连接的, 通过这个连接进行数据传输要遵守串口行为规范(Serial Port Profile, SPP);


该类用法 : BluetoothServerSocket对象时BluetoothAdapter对象调用listenUsingRfcommWithServiceRecord()方法, 调用accept()方法该方法就会将进程阻塞, 如果有BluetoothSock调用connect()方法连接到这个accept()中, 那个这个accept()方法就会返回一个BluetoothSocket对象;


调用BluetoothServerSocket方法的close()方法, 会释放该类占用的资源, 但是该类衍生出的BluetoothSocket对象不会被关闭;


二. 公共方介绍


(1)监听带超时连接

public BluetoothSocket accept (int timeout)
作用 : 该方法会阻塞, 知道监听到一个连接, 或者超时;

参数 : 阻塞时间;

返回值 : 监听到的BluetoothSocket连接;


(2)监听连接

public BluetoothSocket accept ()
作用 : 阻塞一直到连接建立;

返回值 : 监听到的BluetoothSocket连接;


(3)关闭端口

public void close ()
作用 : 关闭端口, 释放该端口占用的资源;

注意 : 如果这个端口在其它线程中accept()阻塞, 那么就会跑出异常, 关闭这个端口不会关闭accept()方法返回的BluetoothSocket对象;









原文地址:https://www.cnblogs.com/hanshuliang/p/4215465.html