2012-07-05 75 views
0

我是Socket的新手,我嘗試在同一個應用程序上編寫一個服務器和客戶端,以瞭解它是如何工作的。套接字 - 地址已被使用

代碼:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    ((Button)this.findViewById(R.id.bouton1)).setOnClickListener(this); 

} 


public void onClick(View v) { 
    TCPServer server = new TCPServer(); 
    TCPClient client = new TCPClient(); 
    server.start(); 
    client.start();  
} 

public class TCPServer extends Thread { 
    @Override public void run() { 

     try { 

      ServerSocket s = new ServerSocket(8080,0,InetAddress.getLocalHost()); 
      Socket cli = s.accept(); 

      byte[] b = new byte[512]; 
      int n; 

      InputStream is = cli.getInputStream(); 
      while((n=is.read(b))>0){ 
       Log.d("TCPServer",new String(b)); 
       if(new String(b).contains("\r\n\r\n"))break; 
       b = new byte[512]; 
      } 

      OutputStream os = cli.getOutputStream(); 
      os.write("Hello".getBytes()); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 



    } 
} 
public class TCPClient extends Thread {  
    @Override public void run() { 

     try { 
      Socket s = new Socket(InetAddress.getLocalHost().getHostAddress(),8080); 
      //Socket s = new Socket("www.google.com",80);        
      //Log.i("",s.getLocalAddress().getHostAddress()); 

      byte[] b = new byte[512]; 
      int n; 

      if (s.isConnected()) { 

       OutputStream os = s.getOutputStream(); 
       os.write("Hi How are you \r\n\r\n".getBytes()); 

       InputStream is = s.getInputStream(); 
       while((n=is.read(b))>0){ 
        Log.d("TCPClient",new String(b)); 
        b = new byte[512]; 
       } 

      } 

      s.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 


    } 
} 

代碼做工精細,但只是在第一次我點擊我的按鈕。 錯誤是java.net.BindException: Address already in use

回答

0

如果它第一次工作,但不是在此之後,它聽起來像你在你的程序退出之前沒有正確關閉你的套接字。

您可以檢查,看它是否仍然運行

netstat 

您不能在Windows機器上掛起開放。我相信他們有類似的東西。

+0

AIE關閉ServerSocket,我知道了。我忘了關閉我的'ServerSocket' – 113408 2012-07-05 21:23:33

+1

netstat存在於Windows中 – 2012-07-05 21:41:56

+0

必須調用'ServerSocket' ** close()**方法 – 113408 2012-07-05 23:05:35

0

對不起,我只是忘了後打開它

相關問題