简体   繁体   English

套接字-地址已在使用中

[英]Socket - Address already in use

I'm new to Socket and I try to code an Server and Client on the same application just to see how it work. 我是Socket新手,我尝试在同一应用程序上编写Server和Client的代码,只是为了查看其工作方式。

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 . 错误是java.net.BindException: Address already in use

If it works the first time, but not after that it sounds like you aren't closing your socket correctly before your program exits. 如果它是第一次运行,但之后没有运行,这听起来像是在程序退出之前没有正确关闭套接字。

You can check to see if it's still open by running 您可以通过运行查看它是否仍然打开

netstat

pending your not on a windows machine. 等待您不在Windows机器上。 I'm sure they have something similar. 我确定他们有类似的东西。

对不起,我只是忘了打开ServerSocket之后将其关闭

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM