Java聊天客户端连接到服务器

时间:2012-01-31 16:34:24

标签: java

我创建了一个与telnet一起使用的聊天服务器。现在,我正在尝试编写自己的客户端。我需要能够从用户获得IP地址和端口号。我试图通过ChatClient()传递这些变量。但是,当我编译以下代码时,我收到以下错误消息:

ChatClient.java:24: cannot find symbol
symbol  : variable ip
location: class ChatClient
            new ChatClient(ip,port);
                           ^
ChatClient.java:24: cannot find symbol
symbol  : variable port
location: class ChatClient
            new ChatClient(ip,port);
                          ^
2 errors

ChatClient.java

public class ChatClient {
    PrintWriter output;
    BufferedReader input;
    Socket client;

    public ChatClient(int ip, int port) throws Exception {
        String line;
        input = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
        output = new PrintWriter(client.getOutputStream(),true);
        output.println("Enter an ip address: ");
        line = input.readLine();
        output.println("Enter a port number: ");
        line = input.readLine();
    }

    public static void main(String ... args) {
        try {
            new ChatClient(ip,port);
        } catch(Exception ex) {
            out.println( "Error --> " + ex.getMessage());
        }

    } // end of main        

}

2 个答案:

答案 0 :(得分:2)

在执行new ChatClient(ip,port)之前,您需要在代码中声明int ipint port个变量:

public static void main(String... args) {
    try {
        int ip = 0;
        int port = 8080;
        new ChatClient(ip,port);
    } catch(Exception ex) {
        ...
    }
}

顺便说一句,如果您要从控制台读取IP地址和端口,可以从int ip, int port的构造函数中删除ChatClient个参数。

答案 1 :(得分:1)

yatskevich为您的编译错误提供了答案,但您的代码还有其他问题。

您希望ChatClient构造函数对ip和端口做什么?它当前通过Socket的OutputStream发送提示,然后通过其InputStream等待Socket的输入。然后忽略输入。

public ChatClient() throws Exception {
    String line;
    int ip, port;
    input = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
    output = new PrintWriter(client.getOutputStream(),true);

    output.println("Enter an ip address: ");
    line = input.readLine();
    if ( line == null ) {
        //EOF - connection closed
        throw new EOFException( "EOF encountered before ip address input." );
    }
    try {
        ip = Integer.parseInteger( line );
    } catch (NumberFormatException nan) {
        //Invalid input
        //    log the error and throw the exception or use a default value.
    }

    output.println("Enter a port number: ");
    line = input.readLine();
    if ( line == null ) {
        //EOF - connection closed
        throw new EOFException( "EOF encountered before port input." );
    }
    try {
        port = Integer.parseInteger( line );
    } catch (NumberFormatException nan) {
        //Invalid input
        //    log the error and throw the exception or use a default value.
    }
}

现在您已经从Socket中读取了端口和IP地址。

Socket来自哪里?我怀疑你真正想要的是:

  1. 从命令行参数中获取IP地址和端口。
  2. 打开指向地址和端口的套接字。
  3. 使用新创建的Socket实例创建客户端实例。