Java新套接字连接被拒绝

时间:2016-01-31 07:20:13

标签: java sockets

我正在尝试编写一个简单的代理服务器,我发现这个代码在线,我只想尝试运行它看看它是否有效,但是当它创建一个新套接字时,它得到一个ConnectException,表示Connect被拒绝。我正在使用'localhost'作为主机,我尝试了几个不同的端口,但没有任何作用。这里有什么问题,是代码还是我的机器?

public static void runServer(String host, int remotePort, int localPort) throws IOException {

    // Create the socket for listening connections
    ServerSocket mySocket = new ServerSocket(localPort);

    final byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (true) {
        Socket client = null, server = null;

        try {
            client = mySocket.accept();

            final InputStream streamFromClient = client.getInputStream();
            final OutputStream streamToClient = client.getOutputStream();

            try {
                server = new Socket(host, remotePort);
            } catch (IOException e) {
                PrintWriter out = new PrintWriter(streamToClient);
                out.print("Proxy server cannot connect to " + host + ":"
                + remotePort + ":\n" + e + "\n");
                out.flush();
                client.close();
                continue;
            }

            final InputStream streamFromServer = server.getInputStream();
            final OutputStream streamToServer = server.getOutputStream();

            Thread t = new Thread() {
                public void run() {
                    int bytesRead;
                    try {
                        while ((bytesRead = streamFromClient.read(request)) != -1) {
                            streamToServer.write(request, 0, bytesRead);
                            streamToServer.flush();
                        }
                    } catch (IOException e) {
                    }
                }
            };

            t.start();

            int bytesRead;
            try {
                while ((bytesRead = streamFromServer.read(reply)) != -1) {
                    streamToClient.write(reply, 0, bytesRead);
                    streamToClient.flush();
                }
            } catch (IOException e) {
            }
            streamToClient.close();

        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try {
                if (server != null)
                    server.close();
                if (client != null)
                    client.close();
            } catch (IOException e) {
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

'拒绝连接'意味着一件事:没有人在IP:你试图连接的端口。所以这是错的。解决方案是使其正确,或者启动服务器(如果尚未启动)。

答案 1 :(得分:-1)

您需要在从套接字读取数据时设置超时,有一个示例here