1

我今天从大学获得了这个示例代码,它在大学内部运行良好,但是当我在家用机器上运行它(使用 Eclipse)时,我的权限被拒绝。大学的机器是Windows(7),我家的电脑是Linux(Ubuntu)。

为什么我会收到以下错误?

I/O 权限错误被拒绝

我正在使用端口 338。

代码副本:

import java.io.*;
import java.net.*;
import java.util.*;

public class Server 
{
    public static void main(String[] args)
    {
        try
        {
            // First create the input from the keyboard
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Server Program");

            // Get the port to listen on
            System.out.print("Enter port number to listen on: ");
            String port_string = input.readLine();

            // The port number needs to be an int, so convert the String to an int
            int port = Integer.parseInt(port_string);

            // Create a ServerSocket to listen on this address
            ServerSocket server = new ServerSocket(port);

            // Accept an incoming client connection on the server socket
            Socket sock = server.accept();

            // Create the output stream to the client
            DataOutputStream network = new DataOutputStream(sock.getOutputStream());

            // Send message
            network.writeUTF("Welcome " + sock.getInetAddress().getHostName() + ". We are " + new Date() + "\n");

            // Close sockets.  This will cause the client to exit
            sock.close();
            server.close();
        }
        catch (IOException ioe)
        {
            System.err.println("Error in I/O");
            System.err.println(ioe.getMessage());
            System.exit(-1);
        }
    }
}
4

2 回答 2

3

1024 以下的端口在大多数现代操作系统(包括 Ubuntu)上具有特权,并且需要您以管理员/root 或提升的特权运行程序。

在家中尝试使用更高的端口进行测试,您应该没问题。

于 2012-10-05T10:16:02.710 回答
2

你说你的家用机器正在运行 Ubuntu。

在 Ubuntu(和其他类 Unix 操作系统)上,普通用户不允许监听小于 1024 端口的端口。

尝试使用 >= 1024 的端口号运行它。

于 2012-10-05T10:16:42.007 回答