[英]Java chat client connecting to server
我创建了一个与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
}
在执行new ChatClient(ip,port)
之前new ChatClient(ip,port)
您需要在代码中声明int ip
和int port
变量:
public static void main(String... args) {
try {
int ip = 0;
int port = 8080;
new ChatClient(ip,port);
} catch(Exception ex) {
...
}
}
顺便说一句,如果您要从控制台读取IP地址和端口,则可以从ChatClient
的构造函数中删除int ip, int port
参数。
yatskevich提供了您的编译错误的答案,但是您的代码还有其他问题。
您希望ChatClient构造函数对ip和port做什么? 当前,它通过套接字的OutputStream发送提示,然后等待套接字通过其InputStream的输入。 然后,它将忽略输入。
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.
}
}
现在,您已经从套接字读取了端口和IP地址。
套接字来自哪里? 我怀疑您真正想要的是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.