在辅助/虚拟IP上创建的套接字拒绝连接

时间:2016-03-27 03:54:14

标签: java linux sockets networking

我使用以下命令在我的机器的eth0接口上创建了两个虚拟IP地址:

sudo ip address add 10.1.1.10/24 dev eth0
sudo ip address add 10.1.1.11/24 dev eth0

他们出现如下:

ip address show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc pfifo_fast state UP group default qlen 1000
....
inet 10.1.1.10/24 scope global eth0
valid_lft forever preferred_lft forever
inet 10.1.1.11/24 scope global secondary eth0
valid_lft forever preferred_lft forever
.....

现在,我想在这两个接口上创建服务器 - 客户端连接。但是,当我刚刚启动服务器代码时,我编写的代码会抛出以下错误。

java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at java.net.Socket.connect(Socket.java:538)
        at java.net.Socket.<init>(Socket.java:434)
        at java.net.Socket.<init>(Socket.java:211)
        at Server.main(Server.java:12)

以下是我的服务器代码:

        try {
        ServerSocket ssoc = new ServerSocket(60000, 0, InetAddress.getByName("10.1.1.10"));
        Socket clientSocket = ssoc.accept();
        OutputStreamWriter osw = new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8");
        InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream(), "UTF-8");
        while (true) {
            String str = "Hello Client";
            osw.write(str, 0, str.length());
            osw.flush();
            char[] input = new char[5000];
            while(isr.ready()) {
                isr.read(input, 0, input.length);
            }
            System.out.println("Client: " + new String(input));
        }

        } catch (IOException e) {
            e.printStackTrace();
        }

我不知道我在这里缺少什么。我的一个想法是,socket()可能需要某种到10.1.1.x网络的路由,但这只是一个模糊的想法。请帮助。

编辑:我根据EJP在评论中的建议编辑了上面的服务器代码。以下是我的客户端代码,现在两个代码正在通信。

try {
            Socket soc = new Socket("10.1.1.10", 60000);
            OutputStreamWriter osw = new OutputStreamWriter(soc.getOutputStream(), "UTF-8");
            InputStreamReader isr = new InputStreamReader(soc.getInputStream(), "UTF-8");
            while (true) {
                String str = "Hello Server";
                osw.write(str, 0, str.length());
                osw.flush();
                char[] input = new char[5000];
                while(isr.ready()) {
                    isr.read(input, 0, input.length);
                }
                System.out.println("Server: " + new String(input));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

0 个答案:

没有答案