java - EC2机器之间的套接字连接

标签 java sockets amazon-ec2 nio

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

服务器.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

我没有得到任何输出,因为我认为没有连接。

最佳答案

检查EC2的“安全组”是否配置了要使用的1111端口的入出规则。

关于java - EC2机器之间的套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36468348/

相关文章:

java - 使用模乘逆查找字符串的秩(有重复项)

php - PHP的fSockOpen查询到服务器?

sockets - 套接字是应用程序通过 Internet 进行通信的唯一方式吗?

java - 从servlet请求jsp中定义的变量?

java - 谁定义了状态模式中的状态转换?

java - 使用 GDB 更改 JVM 中的变量值

java - 用 Java 6 编写 FTP 客户端

amazon-ec2 - 当实例初始化后启动进程时,有没有办法在我的 ec2 实例上公开端口?

git - -bash : hooks/post-receive: Permission denied

amazon-ec2 - AWS 上的 GridGain 集群在 VPC 中使用 TcpDiscoverySpi,而不是集群