EC2机器之间的插座连接

时间:2016-04-07 06:32:56

标签: java sockets amazon-ec2 nio

我正在尝试在我拥有的两个EC2实例之间建立服务器套接字连接。在一台机器上,我有Server.java代码,另一台有Client.java代码。 我没有收到任何错误,但客户端代码无法连接到服务器。

Server.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MasterServer {

    @SuppressWarnings("unused")
    public static void main(String[] args) throws IOException {

        // Selector: multiplexor of SelectableChannel objects
        Selector selector = Selector.open();

        // ServerSocketChannel: selectable channel for stream-oriented listening sockets
        ServerSocketChannel channel = ServerSocketChannel.open();
        InetSocketAddress addr = new InetSocketAddress(1111);

        // Binds the channel's socket to a local address and configures the socket to listen for connections
        channel.bind(addr);

        // Adjusts this channel's blocking mode.
        channel.configureBlocking(false);

        int ops = channel.validOps();
        SelectionKey selectKy = channel.register(selector, ops, null);

        // Infinite loop..
        // Keep server running
        while(true){
            log("i'm a server and i'm waiting for new connection and buffer select...");
            // Selects a set of keys whose corresponding channels are ready for I/O operations
            selector.select();

            // token representing the registration of a SelectableChannel with a Selector
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();

            while (iterator.hasNext()) {
                SelectionKey myKey = iterator.next();

                // Tests whether this key's channel is ready to accept a new socket connection
                if (myKey.isAcceptable()) {
                    SocketChannel client = channel.accept();

                    // Adjusts this channel's blocking mode to false
                    client.configureBlocking(false);

                    // Operation-set bit for read operations
                    client.register(selector, SelectionKey.OP_READ);
                    log("Connection Accepted: " + client.getLocalAddress() + "\n");

                    // Tests whether this key's channel is ready for reading
                } else if (myKey.isReadable()) {

                    SocketChannel client = (SocketChannel) myKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(256);
                    client.read(buffer);
                    String result = new String(buffer.array()).trim();

                    log("Message received: " + result);

                    if (result.equals("Crunchify")) {
                        client.close();
                        log("\nIt's time to close connection as we got last company name 'Crunchify'");
                        log("\nServer will keep running. Try running client again to establish new connection");
                    }
                }
                iterator.remove();
            }
        }
    }
    private static void log(String str) {
        System.out.println(str);
    }
}

Client.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

public class Client {

    public static void main(String[] args) throws IOException, InterruptedException {
        InetSocketAddress addr = new InetSocketAddress("52.201.235.57", 1111);
        SocketChannel client = SocketChannel.open(addr);

        log("Connecting to Server on port 1111...");

        ArrayList<String> companyDetails = new ArrayList<String>();

        // create a ArrayList with companyName list
        companyDetails.add("Facebook");
        companyDetails.add("Twitter");
        companyDetails.add("IBM");
        companyDetails.add("Google");
        companyDetails.add("Crunchify");

        for (String companyName : companyDetails) {

            byte[] message = new String(companyName).getBytes();
            ByteBuffer buffer = ByteBuffer.wrap(message);
            client.write(buffer);

            log("sending: " + companyName);
            buffer.clear();

            // wait for 2 seconds before sending next message
            Thread.sleep(2000);
        }
        client.close();
    }

    private static void log(String str) {
        System.out.println(str);
    }
}

我可以在本地连接它们,但不能在EC2机器上连接,这是我的主要目标。当我运行它们时,我得到以下状态

对于服务器:

^C[root@ip-172-31-59-2 ec2-user]# java Server
i'm a server and i'm waiting for new connection and buffer select...

对于客户:

^C[root@ip-172-31-51-12 ec2-user]# java Client

我没有输出,因为我认为没有连接。

1 个答案:

答案 0 :(得分:1)

检查&#34;安全组&#34; EC2是否为要使用的端口1111配置了传入和传出规则。