Socket - Adress already in use

Posted by Hamza Karmouda on Stack Overflow See other posts from Stack Overflow or by Hamza Karmouda
Published on 2012-07-05T21:13:36Z Indexed on 2012/07/05 21:15 UTC
Read the original article Hit count: 220

Filed under:
|

I'm new to socketand i try to code an Server and client on the same application just to see how it work. here's my code :

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();
        } 


    }
}

the code work fine but just for the first time i click my button. the error is java.net.BindException: Address already in use .

© Stack Overflow or respective owner

Related posts about android

Related posts about sockets