java socket-服务器端 同一个端口 new两次.md[亲测有效]

java socket-服务器端 同一个端口 new两次.md[亲测有效]报错端口被占用应用层代码源码分析原因分析端口被占用

报错

端口被占用

java.net.BindException: Address already in use

	at java.net.PlainSocketImpl.socketBind(Native Method)

	at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)

	at java.net.ServerSocket.bind(ServerSocket.java:376)

	at java.net.ServerSocket.<init>(ServerSocket.java:237)

	at java.net.ServerSocket.<init>(ServerSocket.java:128)

	at serverMaxConn.Server.main(Server.java:21)


应用层代码

//创建服务器端套接字

				ServerSocket ss = new ServerSocket(8888);



源码分析

public

class ServerSocket implements java.io.Closeable {


public void bind(SocketAddress endpoint, int backlog) throws IOException {

        if (isClosed())

            throw new SocketException("Socket is closed");

        if (!oldImpl && isBound())

            throw new SocketException("Already bound");

        if (endpoint == null)

            endpoint = new InetSocketAddress(0);

        if (!(endpoint instanceof InetSocketAddress))

            throw new IllegalArgumentException("Unsupported address type");

        InetSocketAddress epoint = (InetSocketAddress) endpoint;

        if (epoint.isUnresolved())

            throw new SocketException("Unresolved address");

        if (backlog < 1)

          backlog = 50;

        try {

            SecurityManager security = System.getSecurityManager();

            if (security != null)

                security.checkListen(epoint.getPort());

            getImpl().bind(epoint.getAddress(), epoint.getPort());

            getImpl().listen(backlog);

            bound = true;

        } catch(SecurityException e) {

            bound = false;

            throw e;

        } catch(IOException e) {

            bound = false;

            throw e; //捕获异常

        }

    }


abstract class AbstractPlainSocketImpl extends SocketImpl

{




/** * Binds the socket to the specified address of the specified local port. * @param address the address * @param port the port */

    protected synchronized void bind(InetAddress address, int lport)

        throws IOException 

    {

       synchronized (fdLock) {

            if (!closePending && (socket == null || !socket.isBound())) {

                NetHooks.beforeTcpBind(fd, address, lport);

            }

        }

        socketBind(address, lport); //发生异常 向上抛出异常

        if (socket != null)

            socket.setBound();

        if (serverSocket != null)

            serverSocket.setBound();

    }


原因分析

端口被占用

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/13412.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注