当前位置: 代码迷 >> Android >> socket中如何发送和接收数据
  详细解决方案

socket中如何发送和接收数据

热度:55   发布时间:2016-05-01 13:27:47.0
求助 socket中怎么发送和接收数据
我想用蓝牙通信实现名片交换,现在先试验将名片中的名字(string类型)通过蓝牙发过去,蓝牙的socket已经建立了,结果发不过去,代码如下

客户端:
private class ClientThread extends Thread {
  private final BluetoothSocket mmSocket;
  private final OutputStream mmOutStream;
  private final InputStream mmInStream;
   
  public ClientThread(BluetoothSocket socket , String exchange_name) {

  System.out.println("进入clientthread,开始write数据流");
   
  mmSocket = socket;
  mmOutStream = mmSocket.getOutputStream();
  mmInStream = mmSocket.getInputStream();

  // 向socket对象所获取的流中发送数据
  try {
  byte[] send = exchange_name.getBytes();
  mmOutStream.write(send);

  } catch (IOException e) { }
   
  //获取socket对象流中数据,看是否收到了服务器端发来的回馈
  byte[] buffer = new byte[1024];
  int bytes;
  while (true) {
  try {
  bytes = mmInStream.read(buffer);
  System.out.println("client:readbytes:"+bytes);
   
  } catch (IOException e) { }
  }
  }

private class ServerThread extends Thread {
  private final BluetoothSocket mmSocket;
  private final InputStream mmInStream;
  private final OutputStream mmOutStream;

  public ServerThread(BluetoothSocket socket) {

  System.out.println("进入severthread,开始read数据流");
  mmSocket = socket;
  mmOutStream = mmSocket.getOutputStream();
  mmInStream = mmSocket.getInputStream();

  //持续监听,直到接收到客户端发来的数据
  byte[] buffer = new byte[1024];
  int bytes;
  while (true) {
  try {
  bytes = mmInStream.read(buffer);
  System.out.println("server:readbytes: "+bytes);
   
  } catch (IOException e) { }
   
  try {
  //服务器回馈一个字符‘o’
  mmOutStream.write('o');
  } catch (IOException e) { }
  }  
  }

运行结果是什么也没收到,是不是read 和write 用错了呢? 到底应该怎么发送一个string类型的东西呢?



------解决方案--------------------
怎么没看到客户端与服务器商进行通讯时的IP地址??
------解决方案--------------------
flush 试试,可能太小了吧
------解决方案--------------------
你不是打印的读得字节数吗?都没打印?Catch IO异常那里打印下异常 看会不会有IO异常
  相关解决方案