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://juejin.im/post/5c51427c6fb9a049b13e9df7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值