2013-10-07 3 views
0

안드로이드 블루투스 내가 만든 간단한 안드로이드 블루투스 클라이언트 - 서버 프로그램을 원하는 클라이언트 서버 연결

서버 코드 :

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    tv1=(TextView)findViewById(R.id.textView1); 
    tv2=(TextView)findViewById(R.id.textView2); 
    mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); 
    try { 
     mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID); 
     mBluetoothAdapter.cancelDiscovery(); 
     mBluetoothSocket=mBluetoothServerSocket.accept(); 
     mInputStream=mBluetoothSocket.getInputStream(); 
     //if(mInputStream.available()>0){ 
      mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream)); 
      data = mBufferedReader.readLine(); 
      tv1.setText(data); 
     //} 
      if(mInputStream.available()>0){ 
      data=mBufferedReader.readLine(); 
      tv2.setText(data); 
      x++; 
     } 

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


} 

클라이언트 코드 :

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    lb=(Button)findViewById(R.id.button1); 
    btAdapter = BluetoothAdapter.getDefaultAdapter(); 

     BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC); 
     try { 
     btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 
     btAdapter.cancelDiscovery(); 
     btSocket.connect(); 
     String message = "Hello.............. from....... Android......\n"; 
     outStream = btSocket.getOutputStream(); 
     byte[] msgBuffer = message.getBytes(); 
     outStream.write(msgBuffer); 
     } 
    catch(IOException e){ 
     e.printStackTrace();  
    } 
     lb.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      String m1="msg 2"; 
      byte[] msgBuffer = m1.getBytes(); 
      try { 
       outStream.write(msgBuffer); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    }); 
} 

이 응용 프로그램은 한쪽 모드에서 작동하며, 서버로 메시지를 보내고받은 버퍼를 표시합니다.하지만 서버에서 클라이언트로 메시지를 계속해서 다시 보내야합니다.

어떻게 만드시겠습니까?

혹시 궁금한 점이 있으면 알려주세요. 그것을 공유하십시오.

+0

. [mcve] – EsmaeelE

답변

0

이것은 계속 읽는 데 적합합니다. 시도 해봐.

 try { 
      BufferedReader Reader = new BufferedReader(
        new InputStreamReader(mmSocket.getInputStream())); 

      while(true) 
      {     
       String receivedMsg; 
       while((receivedMsg = Reader.readLine()) != null) 
       { 
        // what you do with your message 
       } 

      } 
     } catch (Exception ex) { 
      System.out.println(ex); 
     } 
+0

예 .. 값을 받고 있지만 서버 응용 프로그램을 닫은 후에 ... 다른 클라이언트 서버 응용 프로그램과 다른 예제가 있다면 ... 제발 보내주십시오 ... 감사합니다 .. – elamathy

0

메시지를 보내려는 다른 스레드가 있어야하며,이 스레드는 메시지를 보내는 스레드 일 수 있습니다. 그런 식으로 UI가 멈추지 않고 계속 메시지를받을 수 있습니다. 이러한 스레드의 예 :

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import android.app.Activity; 
import android.bluetooth.BluetoothSocket; 
import android.content.Intent; 
import android.util.Log; 

public class MessageManager extends Thread { 

private static final String TAG = "MessageListener thread"; 
private BluetoothSocket btConnectedSocket; 
private InputStream inStream; 
private OutputStream outStream; 
private Activity parent; 
private boolean run = true; 

public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException { 
    this.btConnectedSocket = btConnectedSocket; 
    this.parent = parent; 
    inStream = btConnectedSocket.getInputStream(); 
    outStream = btConnectedSocket.getOutputStream();   
} 

/* this method will listen continuously to messages received through the BT socket until you call cancel 
public void run() { 
    byte[] buffer = new byte[1024]; 
    int bytes; 

    while (run) { 
     try { 
      bytes = inStream.read(buffer); 
     } 
     catch(IOException ex) { 
      Log.e(TAG, "error while reading from bt socket"); 

     } 
     parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string 
    } 
} 

/* Call this from the main activity to send data to the remote device */ 
public void write(byte[] bytes) throws IOException{ 
     outStream.write(bytes); 
} 

/* Call this from the main activity to shutdown the connection */ 
public void cancel() { 
    run = false; 
    try { 
     btConnectedSocket.close(); 
    } catch (IOException e) { } 

} 

} 당신은`addressHTC`,`이름, uUID` 같은 몇 가지 선언되지 않은 변수를 정의하고 완전한 클래스 코드를 삽입해야합니다

관련 문제