插座 - 地址已在使用 [英] Socket - Address already in use

查看:198
本文介绍了插座 - 地址已在使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的插座我尝试code对同一应用程序的服务器和客户端只是为了看看它是如何工作的。

I'm new to Socketand I try to code an Server and Client on the same application just to see how it work.

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


    }
}

在code做工精细,但只是在第一次我点击我的按钮。
误差 java.net.BindException:地址已在使用

推荐答案

如果它的工作原理是第一次,但不是以后这听起来像你是不是在程序退出之前正确关闭您的插座。

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

等待您不是在Windows机器上。我敢肯定,他们有类似的东西。

pending your not on a windows machine. I'm sure they have something similar.

这篇关于插座 - 地址已在使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆