import java.net. *; import java.io. *; public class EchoClient{ public static void main(String args[]){ try{ Socket connection = new Socket(args[0], 7); System.out.println("Connection established:"); DataInputStream in = new DataInputStream( connection.getInputStream()); DataOutputStream out = new DataOutputStream( connection.getoutputStream()); String line = new String(""); while(!line.toUpperCase().equals(".QUIT")){ System.out.print("Enter string: "); line = readString(); System.out.println("\tSending string to server... "); out.writeUTF(line); System.out.println("\tWaiting for server response... "); line = in.readUTF(); System.out.println("Received: " + line);} in.close(); out.close(); connection.close(); } catch(UnknownHostException uhe){ System.err.println("Unknon host: " + args[0]); } catch(IOException ioe) { System.err.println("IOException: " + ioe); } } public static String readString(){ String string = new String(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try{ string = in.readLine(); }catch(IOException e){ System. out. println("Console. readString: Unknon error..."); System.exit(-1); } return string;} }哪里错了
时间: 2024-03-23 11:43:40 浏览: 76
java的property配置文件的用法.txt
5星 · 资源好评率100%
代码有一个小写字母错误,它导致了编译错误。第16行中的 `connection.getoutputStream()` 应该改为 `connection.getOutputStream()`。将该行代码更改为以下代码将解决问题:
```
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
```
除此之外,还有一些其他的小问题:
1. 在 `String` 对象初始化时,最好使用 `""` 而不是 `new String()`。
2. 在 `catch` 语句中,应该使用 `System.out.println()` 而不是 `System. out. println()`。
3. 在 `readString()` 方法中,有一个拼写错误,应该是 "unknown" 而不是 "unknon"。
4. 最后,建议在 `catch` 块中输出详细的错误信息,以便更好地调试问题。
修改后的代码如下所示:
```
import java.net.*;
import java.io.*;
public class EchoClient {
public static void main(String args[]) {
try {
Socket connection = new Socket(args[0], 7);
System.out.println("Connection established:");
DataInputStream in = new DataInputStream(connection.getInputStream());
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String line = "";
while (!line.toUpperCase().equals(".QUIT")) {
System.out.print("Enter string: ");
line = readString();
System.out.println("\tSending string to server... ");
out.writeUTF(line);
System.out.println("\tWaiting for server response... ");
line = in.readUTF();
System.out.println("Received: " + line);
}
in.close();
out.close();
connection.close();
} catch (UnknownHostException uhe) {
System.err.println("Unknown host: " + args[0]);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
public static String readString() {
String string = "";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
string = in.readLine();
} catch (IOException e) {
System.err.println("Console.readString: Unknown error...");
System.exit(-1);
}
return string;
}
}
```
希望这可以帮助您解决问题!
阅读全文