android socket 编程总结

一   Android 与PC 通讯:

  • PC : Java Server
  • Android :Java Client

Java Server 源代码:

public class PCSERVER implements Runnable {

 

    public static final String PCIP = "192.168.0.254" ;

    public static final int PCPORT = 55555;

 

    public void run() {

       try {

           System. out .println( "connecting......." );

 

           ServerSocket serverSocket = new ServerSocket( PCPORT );

           // 不断获取与客户端的连接(允许与多个客户端进行连接)

 

           while true ) {

              // 获取与一个客户端的连接

              Socket client = serverSocket.accept();

              System. out .println( "S: Receiving..." );

 

              try {

                  // 获取与某个连接上的客户端的输入流

                  BufferedReader in = new BufferedReader(

                         new InputStreamReader(client.getInputStream()));

                  String clientConent = in.readLine();

                 

                  // 打印出服务端接收的客户端的信息

                  System. out .println( "Client:  " + clientConent );

              } catch (Exception e) {

                  System. out .println( "Server Receive: Error" );

                  e.printStackTrace();

              } finally {

                  client.close();

                  System. out .println( "Server Receive: Done." );

              }

 

           }

 

       } catch (Exception e) {

           System. out .println( "S: Error" );

           e.printStackTrace();

       }

    }

 

    public static void main(String a[]) {

       Thread desktopServerThread = new Thread( new PCSERVER());

       desktopServerThread.start();

    }

}

对上边的源代码做一些介绍: 
指定Server 监听的端口和服务器IP 地址。

1

public static final String PCIP = "192.168.0.254";

2

public static final int PCPORT = 55555;

应用之前所指定的IP 和Port 创建一个ServerSocket 对象。

1

ServerSocket serverSocket = new ServerSocket(PCPORT);

用于侦听和捕捉通过Socket 连接的客户端。

1

Socket client = serverSocket.accept();

应用Socket 创建 BufferedReader 对象 , 用于接收Socket Stream 中的数据。

1

BufferedReader in = new BufferedReader(newInputStreamReader(client.getInputStream()));

Android Client 源代码:

public class ClientActivity extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       // TODO Auto-generated method stub

       super .onCreate(savedInstanceState);

       InetAddress serverAddr;

       Socket socket = null ;

       String message = "" ;

       try {

           serverAddr = InetAddress.getByName ( "192.168.0.254" );

           Log.d ( "TCP" , "C: Connecting..." );

          

           // 与服务器获取连接

           socket = new Socket(serverAddr, 55555);

           message = "Hello eoeandroid !" ;

       } catch (UnknownHostException e1) {

           // TODO Auto-generated catch block

           e1.printStackTrace();

       } // TCPServer.SERVERIP

       catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

      

       try {

           Log.d ( "TCP" , "C: Sending: '" + message + "'" );

          

           // 获取 Client 端的输出流

           PrintWriter out = new PrintWriter( new BufferedWriter(

                  new OutputStreamWriter(socket.getOutputStream())), true );

           out.println(message);

        } catch (Exception e) {

           Log.e ( "TCP" , "S: Error" , e);

       } finally {

           try {

              socket.close();

           } catch (IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }

       }

 

    }

}

对上边的源代码做一些介绍: 
指定Server 的IP 地址。

1

InetAddress serverAddr = InetAddress.getByName("192.168.0.254");

应用Server 的IP 和端口建立Socket 对象。

1

Socket socket = new Socket(serverAddr, 55555);

根据已经建立的Socket 来创建PrintWriter ,将信息通过这个对象来发送给Server ,其中包含了三个部分:

1

PrintWriter out = new PrintWriter( new BufferedWriter( newOutputStreamWriter(socket.getOutputStream())),true);

 

 

 

二     Android 蓝牙通讯:

Package name: android.bluetooth.* , 主要相关类介绍如下:

  • BluetoothAdapter: 本地蓝牙设备的适配类,所有的蓝牙操作都要通过该类完成;
  • BluetoothDevice: 蓝牙设备类,代表了蓝牙通讯过程中的远端设备;
  • BluetoothSocket: 蓝牙通讯套接字,代表了与远端设备的连接点,使用socket 本地程序可以通过inputstream 和outputstream 与远端程序进行通讯;
  • BluetoothServerSocket: 服务器通讯套接字,与TCP ServerSocket 类似;
  • BluetoothClass: 用于描述远端设备的类型,特点等信息,通过getBluetoothClass() 方法获取代表远端设备属性的BluetoothClass 对象。

使用蓝牙必须获取的权限:

一定要在AndroidManifest.xml 配置文件中配置上一下两个权限否则蓝牙设备是不可用的

<uses-permission android:name="android.permission.BLUETOOTH" />

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

建立蓝牙连接:

通过BluetoothAdapter.getDefaultAdapter() 方法获取BluetoothAdapter 对象。

判断当前蓝牙是否启动,如果没有启动提示用户手动启动:

if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

在Activity 的onActivityResult() 方法中,对用户的设定结果进行处理。

搜寻远端蓝牙设备

首先获取已配对的远端设备:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

然后通过BluetoothAdapter.startDiscovery() 方法启动蓝牙设备的搜寻。这是个异步方法,调用的时候立刻就会返回。为了获得搜寻的结果,必须在用户自己的Activity 中注册一个BroadcastReceiver ,代码如下:

// Create a BroadcastReceiver for ACTION_FOUND
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());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

设置本地设备可以被发现

只有将本地设备设置为可被发现,远端的蓝牙设备才能够找到并和本地设备建立连接。通过下面的代码发送Intent 对象,让用户手动启动可发现设置。

Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

在本地设备可发现的过程中,可以通过注册BroadcastReceiver 监听可发现状态的改变。

 

实现编码片段 :

服务端

UUID uuid = uuid.fromString(“27648B4D-D854-5674-FA60E4F535E44AF7 ″ );

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord(“MyBluetoothApp”, uuid);
BluetoothSocket socket = serverSocket.accept(); // blocks until a connection is accepted
serverSocket.close(); // close the listening socket

 

客户端:

UUID uuid = uuid.fromString(“27648B4D-D854-5674-FA60E4F535E44AF7 ″ ); // UUID of server socket

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = adapter.getRemoteDevice(“00:11:22:33:44:55 ″ ); // BT MAC address of s erver

 

// 发现连接后会获取服务端 socket 套接字 
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);

// 取消主动发现设备 
adapter.cancelDiscovery();

// 与服务端建立连接 
adapter.connect();

 

双方连接上后,就开始读写了

InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(…);
in.read(…);

in.close();
out.close();
socket.close();

 

通信方式跟 socket 通信原理是一样的,只不过协议不一样,但是协议对于用户都是封装的,用户不必担心。

 

posted on 2012-05-01 23:45  n哖苡逅  阅读(11208)  评论(0编辑  收藏  举报

导航